我有两个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
。这段代码有什么问题?
.save
方法在这种情况下返回false并且不存储数据。
答案 0 :(得分:1)
答案 1 :(得分:0)
评论说:
address.logs << log
# log.save
但是代码并没有这么说。 您应该创建传递地址的日志
log = Log.create(:useragent => request.user_agent, :address => address)
将日志推送到日志集后保存日志:
log = Log.new(:useragent => request.user_agent)
address.logs << log
log.save # not a comment, just a self-explaining code
您案例中的关系存储在Log
资源中,因此您应该保存它,而不是Address
。