Search code examples
ruby-on-railsrubyruby-on-rails-4rails-activerecordmodel-associations

Associations in has_many , belong_to in rails


I am stuck at a small problem,but it has been so long for me trying to figure out what am i doing wrong. My scenario is i have a existing model user and now i create another model called `user_comment'. I have created below mentioned details:

User model:

class User < ActiveRecord::Base
has_many :user_comments
end

User_comment Model:

 class UserComment < ActiveRecord::Base
    belongs_to :user
    end

Migration File:

class CreateUserComments < ActiveRecord::Migration
  def change
    create_table :user_comments do |t|
      t.integer :user_id
      t.string  :comments
      t.timestamps
    end
  end
end

After running rake db:migrate i went to rails console and then to setup the relation between two tables i did the following and nothing is working

obj1= User.first

I added first new row in user_comments table and then did ..

obj2= UserComment.first

Doing obj1.obj2= obj2 is giving me

NoMethodError: undefined method `obj2=' for #<User:0x00000005f8e850>
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activemodel-3.2.11/lib/active_model/attribute_methods.rb:407:in `method_missing'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/attribute_methods.rb:149:in `method_missing'
    from (irb):3
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

Please help me how to form an association ..


Solution

  • Where does SmileComment suddenly come from?

    Anyway, there are several things going wrong. First off, I would change the name of your model from UserComment to Comment. The fact that a comment belongs to an user is already made clear through your association. Calling User.first.user_comments seems a bit akward.

    Let us start with a really basic example:

    class User < ActiveRecord::Base
      has_many :comments
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :user
    end
    

    As you did in your migration, the comments needs a user_id to reference the user it belongs to. After running the migration, calling the association is dead simple:

    User.first.comments # Gives all comments belonging to that user
    

    Or:

    Comment.first.user # Gives the user that belongs to that comment