ruby-on-rails - 有 n,属于 Sinatra 中的 DataMapper

标签 ruby-on-rails ruby sinatra datamapper

在 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])

我打赌linknil

当您收到类似错误时

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/

相关文章:

ruby-on-rails - 这可以与 rails 中的 named_scope 一起使用吗?

ruby - 如何在 Ironruby 中使用 Ruby 库

c - Ruby c 扩展 : How can I catch all exceptions, 包括不是 StandardErrors 的东西?

ruby - 使用 Sinatra 和 rspec stub Controller 方法

ruby-on-rails - Rails 无法正常工作

ruby-on-rails - 如何将 Rails 从 3.2.7 更新到 4.0?

.net - 是否有类似于 Ruby 的 Sinatra 的 .NET 框架?

ruby - Sinatra、Mongoid、Heroku、MongoHQ : connecting to Mongodb

ruby-on-rails - rails 上的公共(public)事件 gem

ruby - 如何使用 ruby​​ 和 MiniTest 伪造 Web 服务