订购与第二模型相关的第一模型

我正在研究我的第一个项目与RoR,我需要在两个模型之间创建多对多的关系,但有可能将第一个模型的对象与第二个模型相关联。

假设我有两个以下型号 – 客户 – 路线

我想为许多路由分配许多客户,但是例如存储该协会的存储顺序

-Route 1 --Customer 2, position 1 --Customer 1, position 2 -Route 2 --Customer 3, position 1 --Customer 1, position 2 

我想我必须使用has_many:through和belongs_to并在中间表中创建“position”字段,但是如何使这个字段可访问和编辑?

您可以选择:through

 class Route < ActiveRecord::Base has_many :bookings has_many :routes, :through => bookings end class Booking < ActiveRecord::Base belongs_to :route belongs_to :customer end class Customer < ActiveRecord::Base has_many :bookings has_many :routes, through => :bookings end 

您的预订模型将保留日期/位置,您可以通过以下方式访问它们:

 c = Customer.first c.routes(:include => :bookings, :order => "bookings.position") 
 class Customer < ActiveRecord::Base has_many :routes, :through => :trips ... end class Trip < ActiveRecord::Base belongs_to :customer belongs_to :route // has a ordinal called 'seq' ... end class Route < ActiveRecord::Base has_many :customers, :through => :trips ... end 

您应该能够通过@ customer.routes [0]访问序数字段.seq我没有测试过它,我的导轨技能很长时间,但你应该明白这个想法。

引用的解决方案是正确的。 要访问中间表,请尝试:

 c.bookings # this will return the 'middle table' which then you have the access to the positions c.bookings.first.position 

我想将所有客户分配显示到一个路由,因此发送到数据库的查询是:

SELECT customers 。* FROM customers INNER JOIN bookings customers .id = bookings .customer_id WHERE(( bookings .route_id = 1))

然后

选择bookings 。*从bookings哪里( bookings .customer_id IN(1,2,3))

..因此,第二个查询在WHERE calus中不包含enought信息,因为它为特定客户选择所有路径的信息,而不仅仅是针对特定路径的特定客户(id = 1)。

..在获取此数据后,RoR是否进行了一些额外的过滤?

顺便说一句。 我有:include =>:预订添加到Route模型中