2012-11-17 27 views
0

嗨,我想了解如何與某些條件的關係工作。我試圖讓消息屬於用戶,我的消息模型與2個用戶(接收者和發送者)相關聯。同時,用戶有2個不同的消息(發送+接收)。Rails窗體:如何將用戶連接到特定類型的消息(接收到消息而不是發送消息)?

從我的研究,似乎這是要走的路:

用戶模型

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 

不過,我有時間構思如何我將在表單中指定什麼類型的用戶(發送者或接收者)和什麼類型的消息(接收或發送)。

(比方說,我有身份驗證)在哪裏/我將如何規定,這種形式的@user應該有這樣的消息加入到他/她的@user.received_messages,而current_user(不管是誰登錄)已此消息被添加到current_user.sent_messages ?這是否在創建操作下的消息控制器中?我不知道如何將@user.id = sender_idcurrent_user.id = receiver_id的值(或者我是否需要這樣做)。謝謝!

回答

2

您只需創建帶有正確用戶標識的消息記錄。該關係將確保消息被包括在每個相應用戶的消息列表(發送和接收)中。

您可能附加在控制器中的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 %> 

和Controller,是這樣的:

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 
+0

感謝澄清。但是,我從來沒有見過'<%= f.hidden_​​field,:receiver_id%>'。你能澄清那是什麼嗎?如果我只是將消息作爲嵌套資源在用戶下(所以我會擁有'@ user'和'current_user'),並且只需將您的'@ message.receiver_id = params [:message] [:receiver_id]'替換爲'@message.receiver_id = @ user.id'? – Edmund

+0

'hidden_​​field'只是創建隱藏表單輸入字段的助手,所以表單會沿着receiver_id傳遞。是的,如果你需要在表單中傳遞接收者,那纔是必要的。就像你所描述的那樣,它將作爲一個嵌套的資源路線工作。 – numbers1311407

相關問題