これまでのところ、テーブルに を格納するfrom
列があることを理解しました。したがって、呼び出すと、. 次に、次のことができますmessages
user_id
message.from
user_id
class Message < AR::Base
belongs_to :user, :foreign_key=>'from'
end
コントローラーで
@messages = Message.all.includes(:user)
#It will load messages and will associated users eager loaded.
message.user.name
ビューで、ユーザーの名前を直接取得するために呼び出すことができます。ビューにこれらの次の2行はまったく必要ありません
<% user_id = message.from %>
<% user = User.find(user_id) %>
何か見逃した場合はお知らせください。
アップデート:
これが私が試したものです
ユーザーモデル
class User < ActiveRecord::Base
attr_accessible :age, :name
has_many :sent_messages, :class_name=>'Message', :foreign_key => 'from'
has_many :received_messages,:class_name=>'Message', :foreign_key => 'user_id'
end
#Contains Data:
#<User id: 1, name: "p1", age: 27, ... ...>,
#<User id: 2, name: "p2", age: 25, ... ...
メッセージ モデル
class Message < ActiveRecord::Base
attr_accessible :body, :sender, :title, :receipent
belongs_to :sender, :class_name => 'User', :foreign_key => 'from'
belongs_to :receipent, :class_name => 'User', :foreign_key => 'user_id'
end
p1
にメッセージを送信するとします。p2
p1.sent_messages.create(title: "test title", body: "test body", receipent: p2)
#Result:
#<Message id: 1, title: "test title", body: "test body", user_id: 2, from: 1 ... ... >
の場合、 と の両方を直接message
取得できますsender
receipent
@messages = Message.includes(:sender, :receipent) # You can load only sender or only receipent
#In View
message.sender.name
#OR
message.receipent.name