开发者

help with rails associations

I want to implement a messaging system for my app.

I have users.

What exactly should I do? create a messages model with foreign two user foreign keys??.. what would be the most approproate way of getting this done?

My worry is that if I query "message.user" I wont know if Id be getting the sender of the receiver of the开发者_如何学运维 message


Use two separate foreign keys with approprately named belongs_to relations to distinguish between senders and receivers.

Given a message model with the foreign keys sender_id and receiver_id you can do:

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
  belongs_to :receiver, :class_name => "User", :foreign_key => "receiver_id"
end

Now you'll be able to reference a message's sender using message.sender and receiver using message.receiver.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜