【发布时间】:2012-01-11 00:22:26
【问题描述】:
已更新问题,因为原始问题过于简单,感谢 Aaron McLeod aka AGMCLEOD 帮助强调这一点
我的问题不是我不能让它工作,而是让它按我想要的方式工作。
问题
想象 3 个模型,一个 Company、Branch 和一个 Contact,它们通过 CompanyContacts 模型或查找表链接在一起。
company_contacts 表如下所示:
+------------+-----------+------------+
| company_id | branch_id | contact_id |
+------------+-----------+------------+
我将联系人与分支机构和公司联系起来的理想陈述应该是:
update company_contacts set contact_id = x where branch_id = y AND company_id = z
那么问题来了,这怎么可能使用 ActiveRecord?您是否创建自定义方法来一次性设置它?
我的模型中有什么
公司联系模型
belongs_to :company, :class_name => "Company", :foreign_key => :company_id
belongs_to :branch, :class_name => "Branch", :foreign_key => :branch_id
belongs_to :contact, :class_name => "Contact", :foreign_key => :contact_id
公司模式
has_many :company_contacts
has_many :branches, :through => :company_contacts, :source => :branches
has_many :contacts, :through => :company_contacts, :source => :contacts
分支模型
has_many :company_contacts
has_many :companies, :through => :company_contacts, :source => :companies
has_many :contacts, :through => :company_contacts, :source => :contacts
我希望能够执行以下操作,但这是不可能的
has_one :company, :through => :company_contacts, :source => :company
当然可以模拟
def branch
Branch.companies.first
end
联系模特
has_many :company_contacts
has_many :branches, :through => :company_contacts, :source => :branches
has_many :companies, :through => :company_contacts, :source => :companies
理想情况下,我希望拥有 has_one 分公司和 has_one 公司
我在创建联系人和
+------------+-----------+------------+
| company_id | branch_id | contact_id |
+------------+-----------+------------+
| 1 | 1 | nil |
+------------+-----------+------------+
| nil | 1 | 1 |
+------------+-----------+------------+
什么时候,其实我想要实现的是:
+------------+-----------+------------+
| company_id | branch_id | contact_id |
+------------+-----------+------------+
| 1 | 1 | 1 |
+------------+-----------+------------+
我能想到的唯一方法是创建一个自定义方法
我将继续尝试解决我的问题并发布我的发现 期待您的回复
提前致谢。
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-3.1