这是我的控制台输出,它只是调用我的新闻对象并在命令行中使用它,我只是不明白为什么在显然有用户模型时存在方法错误。
2.0.0-p353 :021 > News
=> News(id: integer, description: string, created_at: datetime, updated_at: datetime)
2.0.0-p353 :022 > @news = News.first
News Load (0.3ms) SELECT "news".* FROM "news" ORDER BY "news"."id" ASC LIMIT 1
=> #<News id: 4, description: "hello", created_at: "2014-03-08 23:08:53", updated_at: "2014-03-08 23:08:53">
2.0.0-p353 :023 > @news
=> #<News id: 4, description: "hello", created_at: "2014-03-08 23:08:53", updated_at: "2014-03-08 23:08:53">
2.0.0-p353 :024 > @news.user
NoMethodError: undefined method `user' for #<News:0x00000101cee080>
from /Users/spencerlong/.rvm/gems/ruby-2.0.0-p353/gems/activemodel-4.0.2/lib/active_model/attribute_methods.rb:439:in `method_missing'
from /Users/spencerlong/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/attribute_methods.rb:155:in `method_missing'
from (irb):24
from /Users/spencerlong/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
from /Users/spencerlong/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
from /Users/spencerlong/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :news
end
news.rb
class News < ActiveRecord::Base
belongs_to :user
end
答案 0 :(得分:1)
您的新闻模型必须为用户提供关联字段(通常称为“user_id”)。这就是它如何知道它属于哪个用户。您可以通过迁移执行此操作。