Spencer Hire
Spencer Hire

Reputation: 763

NoMethodError 'user' in Rails console

Here is my console output, its just calling my news object and using it in the command line, i just don't understand why there is a method error when there is clearly a user model.

 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

Upvotes: 0

Views: 443

Answers (1)

robotcookies
robotcookies

Reputation: 1059

Your News model has to have an association field for the user (usually called 'user_id'). That's how it knows which user it belongs to. You can do this with a migration.

Upvotes: 1

Related Questions