2014-04-05 82 views
1

我想设置多个has_many:通过并行关系。这里是我的2个标准和2个连接模型:Rails has_many:through - >如何设置关联以从多个连接模型中拉取?

User.rb

has_many :ownerships, dependent: :destroy 
has_many :devices, through: :ownerships 

has_many :bookings, dependent: :destroy 
has_many :devices, through: :bookings 

Ownership.rb

belongs_to :user, touch: true, counter_cache: :devices_count 
belongs_to :device, touch: true 

Booking.rb

belongs_to :user, touch: true, counter_cache: :bookings_count 
belongs_to :device, touch: true, counter_cache: :bookings_count 

Device.rb

has_many :ownerships, dependent: :destroy 
has_many :users, through: :ownerships 

has_many :bookings, dependent: :destroy 
has_many :users, through: :bookings 

预期该电流设置不工作,似乎是加盟模式之间的串扰。我希望连接模型能够独立并行(即用户可以拥有关系 - 所有权 - 设备无法预订)。我不在这里寻找嵌套的has_many:through关系。

当我更改设备的用户所有权似乎改变了预订的数量,反之亦然......我应该如何正确设置它的任何想法?

回答

1

我想你已经得到了第一个错误是你同名调用两个协会(users/devices

帮助任何进一步的受访者中,真正的问题是 - >how do you set up an association to pull from multiple join models?


快速修复

的Rails协会按其类为主命名,但BEC冲突的使用,你应该避免设置它们两次。这就是你看到当前问题的原因。一个简单的分辨率会用不同的名字来调用关联:

User.rb 
has_many :ownerships, dependent: :destroy 
has_many :owner_devices, through: :ownerships, class_name: "Device", foreign_key: "ownership_id" 

has_many :bookings, dependent: :destroy 
has_many :booking_devices, through: :ownerships, class_name: "Device", foreign_key: "booking_id" 

我仍然在寻找的信息,你怎么可以设置关联使用两个模型

+0

感谢您的回答,我认为它是在正确的轨道上。你确定foreign_keys正确吗?他们不应该分别为ownership_id和booking_id吗? –

+0

没问题 - 不,我不确定他们是否正确:)我会看看! –

+0

这只是一个快速修复;至于为一个关联提供多组数据 - 我需要了解这个 –

1

这似乎是一个可行的解决方案如下丰富佩克建议:

User.rb

has_many :ownerships, dependent: :destroy 
has_many :device_ownerships, through: :ownerships, class_name: "Device", foreign_key: "device_id", source: :device 

has_many :bookings, dependent: :destroy 
has_many :device_bookings, through: :bookings, class_name: "Device", foreign_key: "device_id", source: :device 

Booking.rb(加入模型)

belongs_to :user, touch: true, counter_cache: :bookings_count 
belongs_to :device, touch: true, counter_cache: :bookings_count 

Ownership.rb(加入模型)

belongs_to :user, touch: true, counter_cache: :devices_count 
belongs_to :device, touch: true, counter_cache: :users_count 

设备。RB

has_many :ownerships, dependent: :destroy 
has_many :user_ownerships, through: :ownerships, class_name: "User", foreign_key: "user_id", source: :user 

has_many :bookings, dependent: :destroy 
has_many :user_bookings, through: :bookings, class_name: "User", foreign_key: "user_id", source: :user 

说实话,我在为什么foreign_key的需要(?)被设置为他们有点糊涂了,所以我必须做更多的阅读了。否则它看起来是功能性的,我没有看到这些连接模型之间的串扰了。

+0

好的工作 - 'foriegn_key'基本上是一个变量,用于定义正确的列名称,如果您使用的是非常规关联。最好将关联视为方法,这些方法具有从名称派生的自动化选项。如果你使用的是非标准名称,你的论点需要修改为sui t :) –

+0

顺便说一句,如果它有帮助,你可能想要提高我的答案;) –

相关问题