0

我有两个 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_s1每个页面重新加载时(应该递增)。当我这样做时(以​​另一种方法):

logs = Address.get(id).logs
@views = logs.length

views总是0。这段代码有什么问题?


好的,所以我尝试推送到字符串字段太长的用户代理。字符串限制为 50 个字符。#datamapper irc 频道上的人帮助了我,.save在这种情况下方法返回 false 并且不存储数据。

4

2 回答 2

1

好的,所以我尝试推送到字符串字段太长的用户代理。字符串限制为 50 个字符。#datamapper irc 频道上的人帮助了我,在这种情况下 .save 方法返回 false 并且不存储数据。

于 2012-11-13T14:08:48.877 回答
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.

于 2012-10-28T13:12:53.583 回答