0

嗨,我想了解在某些条件下的关系是如何运作的。我正在尝试使消息属于用户,我的消息模型与 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?这会在创建操作下的消息控制器中吗?我不确定我将如何设置@user.id = sender_idand的值current_user.id = receiver_id(或者我是否需要这样做)。谢谢!

4

1 回答 1

2

您需要做的就是创建附加了正确用户 ID 的消息记录。该关系将负责确保消息包含在每个相应用户的消息列表(已发送和已接收)中。

您可能会附加在current_user控制器中,因为您从会话中知道此 ID,并且不需要(或不希望)它在表单中。

您可以通过隐藏的 id(或下拉列表等,如果您需要在表单中选择用户)将其receiver包含在表单中。如果您使用隐藏的 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
于 2012-11-17T18:09:28.690 回答