Search code examples
ruby-on-railsassociations

Using Rails' build() method through a renamed association


I have a Message model containing

belongs_to :from, class_name: "User"
belongs_to :to, class_name: "User"

When I do something like

user.messages.build(text: "my message")

how can I ensure the user put into the "from" association is the building user? How does Rails know whether to put it into "from" or "to"?


Solution

  • I think the correct way to set up the message model would be like this:

    belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
    belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'
    

    Your migration would be like

    create_table :messages do |t|
      t.integer :sender_id
      t.integer :recipient_id
      t.timestamps
    end
    

    Then, in the user model:

    has_many :messages, :foreign_key => :sender_id
    

    Then, in the message form you could set the sender like this:

    <%= f.hidden_field :sender_id, value: current_user.id %>
    <%= f.hidden_field :recipient_id, value: @user.id %>
    

    You could also set the parameters like in your example in the question like this:

    Message.create(sender_id: 1, recipient_id: 3)
    

    This should let you do things like:

    @message.sender.username
    @message.recipient.username