2009-09-09 95 views
2

我正在使用RoR開發我的第一個項目,我需要創建兩個模型之間的多對多關係,但有可能將第一個模型的對象與第二個模型關聯起來。訂購與第二個模型關聯的第一個模型

比方說,我有兩個以下型號 - 客戶 - 路由

我想分配了衆多客戶的許多途徑,但與存儲這種關聯的順序,因此,例如

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

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

我想我必須使用has_many:through和belong_to並在中間表中創建「position」字段,但是如何使該字段可訪問和可編輯?

回答

3

你可以用: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") 
+0

那麼您如何在此位置字段上操作?它也會分配給客戶嗎? – Inez 2009-09-09 20:14:38

+0

對於給定的預訂: C = Customer.first B = c.bookings.first b.position 但是上面已經代碼返回,以便路由,則可以只將它傳遞到部分(或環上在控制器中設置的結果)。 – cite 2009-09-09 20:19:43

1
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 我沒有測試過它,我的鐵軌技能很長,但你應該明白。

0

cite的解決方案是正確的。訪問中間表,請嘗試:

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

我要顯示所有客戶assignes一個路線,所以發送到數據庫查詢是:

選擇customers * FROM customers INNER JOIN bookings ON customers。 ID = bookings .customer_id WHERE((bookings .route_id = 1))

然後

SELECT bookings。* FROM bookings WHERE(bookings .customer_id IN(1,2,3))

..所以,第二個查詢不包含在WHERE calus足夠多的信息,因爲它是爲特定客戶的所有路由選擇信息,不只是特定特定路線的客戶(id = 1)。

..是RoR在獲取這些數據後做一些額外的過濾?

btw。我有:include =>:添加到Route模型中的預訂

+0

但第一個查詢正確嗎?第二個查詢預先加載所有預訂的額外查詢,因爲您的Route模型中包含'inlcude'。 'Include'會告訴導軌加載與第一個查詢相關的所有預訂,以備將來使用。 – 2009-09-09 21:56:33

+0

是的,但是在特定的客戶和特定記錄之間沒有關聯,與該用戶和該路線有關,所以我無法獲得位置 – Inez 2009-09-10 09:04:24

相關問題