我是新來的導軌,我在我的應用程序中有一些has_many through:
關係。 我有User, Message
和Message_Recipients
模型(用戶有很多消息,消息有一個發件人,消息有很多收件人 - message_recipients是連接表)。多表導軌查詢
我想在我的消息視圖中顯示郵件發件人的名稱,這是留在用戶模型中。但是,無論我如何嘗試這樣做,我都會收到錯誤 - 我不確定我是否堅持「Rails方式」。
用戶字段是:id, forename, surname, email
消息字段是:id, sender_id, subject, body
SENDER_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。
任何幫助/最佳實踐意見將不勝感激!
這將工作的消息發送給多個用戶雖然?感謝您的答案btw! – Chloe
是的,看看如何保存到一個user_ids數組(你正在使用postgresql,對嗎?) –
我使用sqlite3 ,你會這樣認爲嗎?非常感謝 – Chloe