开发者

rails way user to user messaging, do I need a join table?

开发者 https://www.devze.com 2023-01-22 03:09 出处:网络
Quick question (I think). I have users, and I would like to allow them to send messages to one another.My question is, should I have a user table, a message table, and a users to messages join table,

Quick question (I think). I have users, and I would like to allow them to send messages to one another. My question is, should I have a user table, a message table, and a users to messages join table, or should I just store to_user_id and from_user_id in the messages table. If the latter, what would the associatio开发者_如何学Pythonn look like for that? Can you even reference a 'local' key for an association?


You can do that with a couple of simple has_many associations. Since it's self-referential, you'll need to override some of the Rails magic to make it work.

class User < ActiveRecord::Base
  has_many :sent_messages, :class_name => 'Message', :foreign_key => 'sender_id'
  has_many :received_messages, :class_name => 'Message', :foreign_key => 'recipient_id'
end

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User'
  belongs_to :recipient, :class_name => 'User'
end

Rails doesn't have a cleaner way to doing self-referential associations that I know of.


I think the latter sounds fine. This is just off the top of my head but I know AR's associations have options like this...

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => :user, :foreign_key => :from_user_id
  belongs_to :recipient, :class_name => :user, :foreign_key => :to_user_id
  #...
end

class User < ActiveRecord::Base
  has_many :received_messages, :class_name => :message, :foreign_key => :to_user_id
  has_many :sent_messages, :class_name => :message, :foreign_key => :from_user_id
end
0

精彩评论

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

关注公众号