Search code examples
ruby-on-railsassociations

How to create an object that belongs to two models


Is there any way by which i can create an object of a model that belongs to two other models for example if i have users who have many posts and then posts which can have many comments and comments belongs to both user and post. if i do post.comments.create() it will associate only post with comment and if i do user.comments.create() then it will associate user. If i want to associate both with comments then what's the method for that. I know i can use polymorphic association but is there any other way too?


Solution

  • First things first, when you are talking about associations, you must keep in mind that we build not create. A very simple way to do what you need is do

        class Comment < ActiveRecord::Base
          belongs_to :user
       end
    

    and dont forget to add the other side of the relation in User where:

     class User < ActiveRecord::Base
      has_many :comments
     end
    

    Now, I understand that you must have created a field user_id in comments table. If not, you need to add it by this migration.

    rails g migration add_user_id_to_comments user_id:string
    

    now do a rake db:migrate

    alternatively and a more better method will be .

    while creating the model comments you add users:references in the migration line like this

    rails g model Comment text:string post:references user:references
    

    in this way , one side of the relation will automatically be added to the model and also the user_id and post_id fields will be added automatically to your comments table.

    Coming back to your question. pass user id in a hidden field if you find no other way like this:

    <%= hidden_field_tag "userid", current_user.id%>
    

    I expect thet you have current user defined. now you can accept this in the controller of the comments like this

    If params[:userid]
     user_id = params[:userid]
    end
    

    you can include this just before the save function in the create action of comments controller.

    Hope this helps

    Cheers!