在Rails的多发性关系,其中的类名不匹配协会名称 [英] Multipe relationships in Rails where the class name does not match the association name

查看:318
本文介绍了在Rails的多发性关系,其中的类名不匹配协会名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有涉及到两个用户私人信息的模式,我怎么建立一个协会,使PM.sender是发件人的用户模型和PM.receiver是收件人的用户模式? (这样我可以叫PM.sender.username等。)

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.)

我有一个sender_id和receiver_id领域。

I have a sender_id and receiver_id field.

推荐答案

假设模型类消息用户,在消息型号:

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

由于类的名字不能推导出明确的的关联名称:将class_name 要求

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

更新:刚走选中,:不应该,只要外键的名称是名称需要foreign_key 参数该协会随后 _id ,它是在这种情况下。

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.

这篇关于在Rails的多发性关系,其中的类名不匹配协会名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆