簡體   English   中英

您如何通過關系來使Rails has_many與has_many條件一起工作?

[英]How do you get Rails has_many through relations to work with has_many conditions?

我一直在從事一個大量使用模型關聯的項目,似乎我發現通過功能has_many或has_one與:conditions功能沖突的情況。 簡而言之,問題在於直通關聯在has_one盡管關系中為中間表創建了表別名。 但是我不知道如何使表別名以我定義的條件出現,如果很難遵循,也許代碼會有所幫助:

class Event < ActiveRecord::Base
  has_one :event_intake, :conditions => ['event_intakes.is_draft = 1']
  has_many :product_instances, :through => :event_intake
end

class EventIntake < ActiveRecord::Base
  belongs_to :event
  has_many :product_instances, :conditions => ['is_deleted = ?', '0']
end

class ProductInstance < ActiveRecord::Base
  belongs_to :event_intake
end

這是我得到的MySQL查詢和錯誤:

Mysql2::Error: Unknown column 'event_intakes.is_draft' in 'on clause': 

SELECT DISTINCT `events`.id FROM `events` 
  LEFT OUTER JOIN `event_intakes` product_instances_events_join ON (`events`.`id` = `product_instances_events_join`.`event_id`) 
  LEFT OUTER JOIN `product_instances` ON (`product_instances`.`event_intake_id` = `product_instances_events_join`.`id`) AND event_intakes.is_draft = 1 
WHERE (product_instances.serial_number = '313') ORDER BY events.id DESC LIMIT 0, 50

直通關聯將event_intakes表別名為“ product_instances_events_join”。 但是條件event_intakes.is_draft中的表未更改為與其匹配。

我使用的是Rails 2.3.11,但我認為問題可能同樣適用於rails3。我讀到貫通關聯應僅與has_many一起使用,而不能與has_one一起使用,但是我不認為這是造成此問題的原因問題。

如果我只是將條件更改為“ product_instances_events_join.is_draft = 1”,它將解決此特定情況下的問題,但是在沒有表別名的情況下將其破壞。 如果可以在has_one條件上使用字符串插值來獲取正確的表名,那將是很好的。 像這樣的東西:has_one:event_intake,:conditions => [“#{EventIntake.table_name} .is_draft = 1”]我認為上面的代碼不起作用,因為發生別名時EventIntake的table_name不會改變。

我嘗試過的另一件事是在發生別名之前使用以下命令立即重新定義has_many關聯:在我進行查詢之前:Event.has_one:event_intake,:conditions => ['product_instances_events_join.is_draft = 1']相信它是否可以解決webrick中的問題,但是我不願意在多線程乘客環境中使用此方法,因為我認為這等於修改全局變量,這可能會影響其他線程。 此外,這是一個hack。

有人對如何解決這個問題有任何建議嗎? 任何幫助將不勝感激。

您可以將條件放在:product_instances上

class Event < ActiveRecord::Base
  has_one :event_intake 
  has_many :product_instances, :through => :event_intake,
               :conditions => ['event_intakes.is_draft = 1']
end

在has_one上設置條件似乎有點尷尬,因為您實際上並不是在過濾event_intakes而是打開或關閉整個關聯。 但是我想這不重要。

另外,我確實了解到,如果您要通過中介條件來過濾多個后續的“直通”關聯,那么這並不是很干燥。 那就是我發現自己的地方,這就是我在這里碰巧的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM