到目前为止,我已经了解到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
直接调用以获取用户名。您根本不需要以下两行
<% 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 ... ... >
现在对于 a 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