您好,我正在努力了解某些条件的关系是如何运作的。我正在尝试使消息属于用户,我的消息模型与2个用户(接收者和发送者)链接。同时,用户有2个不同的消息(已发送+已接收)。
从我的研究来看,这似乎是要走的路:
用户模型
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
消息模型
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
但是,我有时间概念化如何在表单中指定哪种类型的用户(发送者或接收者)以及什么类型的消息(接收或发送)。
<%= form_for(@user, @message) do |f| %>
<%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>
(假设我有身份验证)在哪里/如何指定此表单@user
应将此消息添加到他/她@user.received_messages
,而current_user
(无论谁登录) )此消息是否已添加到current_user.sent_messages
?这会在create action下的消息控制器中吗?我不确定如何设置@user.id = sender_id
和current_user.id = receiver_id
的值(或者我是否需要这样做)。谢谢!
答案 0 :(得分:2)
您需要做的就是创建附加了正确用户ID的消息记录。该关系将确保消息被包含在每个相应用户的消息列表中(发送和接收)。
您可能在控制器中附加的current_user
,因为您知道会话中的此ID并且不需要(或想要)它在表单中。
receiver
您可以通过隐藏ID(或下拉列表等)在表单中包含,如果您需要在表单中选择用户。如果您使用隐藏ID,则假定您在呈现表单之前在消息上设置接收器。
类似的东西:
<%= form_for(@message) do |f| %>
<%= f.hidden_field, :receiver_id %>
<%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit %>
<% end %>
在控制器中,例如:
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