在 O'Reilly 书籍的帮助下,我正在使用 Sinatra 和 DataMapper 构建 URL 缩短服务的克隆。当我通过提交缩短的网址来测试它时,我收到此错误
NoMethodError - undefined method `visits' for nil:NilClass:
第 31 行。看起来 Link 类没有访问属性,但是,正如您从下面的类定义中看到的那样,这种关系使得我应该能够调用 link。访问
我正在使用最新版本的 DataMapper。谁能建议解决这个问题?
get '/:short_url' do
link = Link.first(:identifier => params[:short_url])
link.visits << Visit.create(:ip => get_remote_ip(env)) #this is line 32
link.save
redirect link.url.original, 301
end
类(class)
Class Url
include DataMapper::Resource
property :id, Serial
property :original, String, :length => 255
belongs_to :link
end
class Link
include DataMapper::Resource
property :identifier, String, :key => true
property :created_at, DateTime
has 1, :url
has n, :visits
class Visit
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
property :ip, IPAddress
property :country, String
belongs_to :link
after :create, :set_country
最佳答案
我相信这就是您的问题所在:
link = Link.first(:identifier => params[:short_url])
我打赌link
是nil
当您收到类似错误时
NoMethodError - undefined method `visits' for nil:NilClass:
这表示您尝试调用对象 nil
上的方法 visits
。您期望在 Link
对象上调用方法 visits
。
如果您想查找一条记录(如果存在)或创建一条新记录,请尝试以下操作:
Link.first_or_create(:identifier => params[:short_url])
关于ruby-on-rails - 有 n,属于 Sinatra 中的 DataMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273634/