Reputation: 27527
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!
Upvotes: 0
Views: 109
Reputation: 34072
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_user
you might attach in the controller, as you know this id from the session and don't need (or want) it in the form.
The receiver
you 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:
<%= form_for(@message) do |f| %>
<%= f.hidden_field, :receiver_id %>
<%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>
And in the controller, something like:
def create
@message = Message.new(params[:message])
# If receiver_id wasn't attr_accessible you'd have to set it manually.
#
# This makes sense if there are security concerns or rules as to who
# can send to who. E.g. maybe users can only send to people on their
# friends list, and you need to check that before setting the receiver.
#
# Otherwise, there's probably little reason to keep the receiver_id
# attr_protected.
@message.receiver_id = params[:message][:receiver_id]
# The current_user (sender) is added from the session, not the form.
@message.sender_id = current_user.id
# save the message, and so on
end
Upvotes: 2