在 O'Reilly 书籍的帮助下,我正在使用 Sinatra 和 DataMapper 构建一个 url 缩短服务的克隆。当我通过提交用于缩短的 url 对其进行测试时,出现此错误
NoMethodError - undefined method `visits' for nil:NilClass:
对于第 31 行。似乎 Link 类没有访问属性,但是,正如您从下面的类定义中看到的那样,这种关系是我应该能够调用的link.visits
我正在使用最新版本的 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 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