我有两个 DataMapper 模型:
class Address
include DataMapper::Resource
property :id, Serial
property :url, String, :required => true
has n, :logs
end
class Log
include DataMapper::Resource
property :id, Serial
property :useragent, String
belongs_to :address
end
我使用 Sinatra 创建新地址,并在另一种方法中记录属于这些地址的日志。
# page after posting a form
post '/' do
@messages = []
if (params[:url] =~ URI::regexp).nil?
@messages.push('URL is not valid!')
else
address = Address.create(:url => params[:url])
base36 = address.id.to_s(36)
@messages.push(request.url + base36)
end
erb :index
end
# redirection from a short url
get '/:base36' do |base36|
# probably not necessary...
if base36 =~ /[[:alnum:]]+/
begin
id = base36.to_i(36)
address = Address.get(id)
log = Log.create(:useragent => request.user_agent)
address.logs << log
# log.save
address.save
# address.logs.save
address.logs.length.to_s
# redirect address.url
rescue
redirect '/'
end
else
redirect '/'
end
end
问题是,新日志没有存储在数据库中。address.logs.length.to_s
在1
每个页面重新加载时(应该递增)。当我这样做时(以另一种方法):
logs = Address.get(id).logs
@views = logs.length
views
总是0
。这段代码有什么问题?
好的,所以我尝试推送到字符串字段太长的用户代理。字符串限制为 50 个字符。#datamapper irc 频道上的人帮助了我,.save
在这种情况下方法返回 false 并且不存储数据。