Hi I’m trying to understand how relationships with certain conditions work. I’m trying to make Messages belong to Users, with my Messages model linked with 2 users (a receiver and a sender). At the same time, Users have 2 different messages (sent + received).
From my research, it seems like this is the way to go:
Users model
class Users < ActiveRecord::Base
attr_accessible :age, :gender, :name
has_many :sent_messages, :class => "Messages", :foreign_key => 'sender_id'
has_many :received_messages, :class => "Messages", :foreign_key => 'receiver_id'
end
Messages model
class Messages < ActiveRecord::Base
attr_accessible :content, :read
belongs_to :sender, :class => "User", :foreign_key => 'sender_id'
belongs_to :receiver, :class => "User", :foreign_key => 'receiver_id'
end
However, I’m having time conceptualizing how I would specify what type of User (a sender or receiver) and what type of Message (received or sent) in the form.
<%= form_for(@user, @message) do |f| %>
<%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>
(Let’s say I have authentication) Where/How would I specify that this form’s @user should have this message added to his/her @user.received_messages, while current_user(whoever is logged in) has this message be added to current_user.sent_messages ? Would this be in the message controller under the create action? I’m not sure how I would put values of @user.id = sender_id and current_user.id = receiver_id (or whether I need to do that at all). Thanks!
All you need to do is to create the message record with the proper user ids attached. The relation will take care of ensuring that the message is included in each respective user’s list of messages (sent and received).
The
current_useryou might attach in the controller, as you know this id from the session and don’t need (or want) it in the form.The
receiveryou could just include in the form via a hidden id (or a dropdown, etc, if you need to select the user in the form). If you used a hidden id it’s assumed you’re setting the receiver on the message before rendering the form.Something like:
And in the controller, something like: