【问题标题】:Rails forms: How to connect a User with a specific type of Message (received msg instead of sent msg)?Rails 表单:如何将用户与特定类型的消息(接收到的消息而不是发送的消息)联系起来?
【发布时间】:2012-11-18 02:21:50
【问题描述】:

您好,我想了解特定条件下的关系如何运作。我试图让消息属于用户,我的消息模型与 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_idcurrent_user.id = receiver_id 的值(或者我是否需要这样做)。谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您需要做的就是创建带有正确用户 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
    

    【讨论】:

    • 感谢您的澄清。但是,我从未见过&lt;%= f.hidden_field, :receiver_id %&gt;。你能澄清一下这是为了什么吗?如果我只是将消息作为用户下的嵌套资源(所以我将拥有@usercurrent_user)并且只需将您的`@message.receiver_id = params[:message][:receiver_id]` 替换为@,那是否有必要? 987654328@?
    • hidden_field 只是创建隐藏表单输入字段的助手,因此表单将传递receiver_id。是的,只有当您需要在表格中传递接收器时才需要这样做。正如您所描述的,它将作为嵌套资源路由工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2014-02-23
    相关资源
    最近更新 更多