私はレールが新しく、私のアプリにはhas_many through:
の関係があります。 私はUser, Message
とMessage_Recipients
モデルを持っています(ユーザーには多くのメッセージがあり、メッセージには1つの送信者があり、メッセージには多数の受信者があります.- message_recipientsは結合テーブルです)。複数テーブルレールのクエリ
私はUserモデルで保持されているMessageビューにメッセージ送信者の名前を表示しようとしています。しかし、私がこれをやろうとしても、エラーは出ています。私が "the Rails Way"を遵守しているかどうかはわかりません。
ユーザは、次のフィールドがあります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 %>
それは私がに基づいてユーザのforenameの値を取得するように見えることができないとして、私はトラブルを抱えているという見解でありますNoMethodErrorを取得したため、メッセージを送信した人のsender_id。
アドバイス/ベストプラクティスのアドバイスは大変ありがとうございます。
あなたの答えはありがとうbtw! – Chloe
はい、postgresqlを使用しているuser_idsの配列に保存する方法を調べてください。 –
私はsqlite3を使用しています、それはあなたと同じになると思いますか?ありがとう非常にありがとうございます。 – Chloe