Multipe relationships in Rails where the class name does not match the association name

不想你离开。 提交于 2019-12-24 19:39:57

问题


I have a private message model that relates to two users, how do I setup an association so that PM.sender is the sender's user model and PM.receiver is recipient's user model? (so that I can call PM.sender.username etc.)

I have a sender_id and receiver_id field.


回答1:


Assuming model classes Message and User, in your Message model:

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

Because the class name can't be deduced from the association name the explicit :class_name is required.

Update: Having just checked, the :foreign_key parameter shouldn't be required as long as the name of the foreign key is the name of the association followed by _id, which it is in this case.



来源:https://stackoverflow.com/questions/1988915/multipe-relationships-in-rails-where-the-class-name-does-not-match-the-associati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!