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ますか?これは create アクションの下のメッセージ コントローラにありますか? @user.id = sender_idandの値をどのように設定するcurrent_user.id = receiver_idか (または、それを行う必要があるかどうか) がわかりません。ありがとう!

4

1 に答える 1

2

必要な作業は、適切なユーザー ID が添付されたメッセージ レコードを作成することだけです。リレーションは、メッセージが各ユーザーのメッセージのリスト (送信および受信) に確実に含まれるようにします。

セッションからこのcurrent_userid を知っていて、フォームでそれを必要としない (またはしたくない) ため、コントローラーにアタッチすることができます。

非表示のreceiverID (またはフォームでユーザーを選択する必要がある場合はドロップダウンなど) を介してフォームに含めることができます。非表示の 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 に答える