2016-12-04 10 views
1

私はレールが新しく、私のアプリにはhas_many through:の関係があります。 私はUser, MessageMessage_Recipientsモデルを持っています(ユーザーには多くのメッセージがあり、メッセージには1つの送信者があり、メッセージには多数の受信者があります.- message_recipientsは結合テーブルです)。複数テーブルレールのクエリ

私はUserモデルで保持されているMessageビューにメッセージ送信者の名前を表示しようとしています。しかし、私がこれをやろうとしても、エラーは出ています。私が "the Rails Way"を遵守しているかどうかはわかりません。

ユーザは、次のフィールドがあります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 %> 

それは私がに基づいてユーザのforenameの値を取得するように見えることができないとして、私はトラブルを抱えているという見解でありますNoMethodErrorを取得したため、メッセージを送信した人のsender_id。

アドバイス/ベストプラクティスのアドバイスは大変ありがとうございます。

答えて

0

アソシエーションは、考え過ぎることなく十分にトリッキーです。 2つのモデル、ユーザー、メッセージだけが必要です。 メッセージテーブルには、title、text、recipient_id、およびsender_idが含まれます。その人のuser_idにフラグが立てられ、current_userのuser_idが送信者のidのために設定されます。例 Message.create((id will will。送信者のようなサウンドは、データベースの受信者のドロップダウンリストから選択します。あなたのユーザのモデルに :メッセージに属し、メッセージモデルに属しています:ユーザに属しています あなたのコンソールで試してみてください。

+0

あなたの答えはありがとうbtw! – Chloe

+0

はい、postgresqlを使用しているuser_idsの配列に保存する方法を調べてください。 –

+0

私はsqlite3を使用しています、それはあなたと同じになると思いますか?ありがとう非常にありがとうございます。 – Chloe