2016-12-04 57 views
1

我是新來的導軌,我在我的應用程序中有一些has_many through:關係。 我有User, MessageMessage_Recipients模型(用戶有很多消息,消息有一個發件人,消息有很多收件人 - message_recipients是連接表)。多表導軌查詢

我想在我的消息視圖中顯示郵件發件人的名稱,這是留在用戶模型中。但是,無論我如何嘗試這樣做,我都會收到錯誤 - 我不確定我是否堅持「Rails方式」。

用戶字段是:id, forename, surname, email

消息字段是:id, sender_id, subject, bodySENDER_ID是用戶FK

Message_Recipient字段是:id, user_id, message_id用戶/ MESSAGE_ID是FKS

這裏是我的模型(我也在用Devise):

class Message < ActiveRecord::Base 
    belongs_to :user, :class_name => User, :foreign_key => "sender_id"#sender 
    has_many :message_recipients 
    has_many :users, through: :message_recipients 
end 



class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :message_recipients 
    has_many :messages, through: :message_recipients 
end 



class MessageRecipient < ActiveRecord::Base 
    belongs_to :message, :class_name => Message, :foreign_key => "message_id" 
    belongs_to :user, :class_name => User, :foreign_key => "user_id" 
end 

這是我的消息/ index.html.erb:

<% @messages.each do |message| %> 
    <div class="message"> 
    <h2><%= message.subject %></h2> 
    <p>Sent by <%= message.user.forename %></p> 
    </div> 
<% end %> 

正是在這我有麻煩,因爲我似乎無法獲得用戶的基礎上,用的名字的價值的看法由於獲取了NoMethodError,發送消息的人員的sender_id。

任何幫助/最佳實踐意見將不勝感激!

回答

0

關聯可能會非常棘手,而不會超越他們。你只需要兩個模型,用戶和消息。 郵件表格將包含標題,文本,recipient_id和sender_id。 (聽起來就像發件人會從數據庫中的收件人下拉列表中選擇一樣,一旦選擇該人的user_id將被標記,並且current_user的user_id將被設置爲發件人的id另一個字段:Example Message.create((id (自動)發件人(current_user user_id)收件人(user_id),文本:「祝你有美好的一天」) 在用戶模型中:有和屬於消息;在消息模型中:屬於用戶 在控制檯中試用。

+0

這將工作的消息發送給多個用戶雖然?感謝您的答案btw! – Chloe

+0

是的,看看如何保存到一個user_ids數組(你正在使用postgresql,對嗎?) –

+0

我使用sqlite3 ,你會這樣認爲嗎?非常感謝 – Chloe