2013-02-01 50 views
0

我有一些模型類是這樣的:在has_many上找到(:all):通過簡單的不工作?

class Organisation < ActiveRecord::Base 
    has_many :dongles 
    has_many :licences_on_owned_dongles, :through => :dongles, :source => :licences, 
      :include => [:organisation, :user, :owner_organisation, :profile, :dongle, 
         {:nested_licences => [:profile]} ] 
end 

class Dongle < ActiveRecord::Base 
    has_many :licences 
    belongs_to :organisation 
end 

class Licence < ActiveRecord::Base 
    belongs_to :dongle 

    # tree-like structure. I don't remember why this had to be done but the comment says 
    # "find a way to make the simpler way work again" and I tried using the simpler way 
    # but tests still fail. So obviously the SQL awfulness is necessary... 
    default_scope :conditions => { :parent_licence_id, nil } 
    has_many :nested_licences, :class_name => 'Licence', :dependent => :destroy, 
      :autosave => true, 
      :foreign_key => :parent_licence_id, 
      :finder_sql => proc { 
      "SELECT l.* FROM licences l WHERE l.parent_licence_id = #{id}" }, 
      :counter_sql => proc { 
      "SELECT COUNT(*) FROM licences l WHERE l.parent_licence_id = #{id}" } 
end 

現在我可以這樣做:

test "getting licences on owned dongles" do 
    org = organisations(:some_other_corp) 
    assert_equal [licences(:licence_4)], org.licences_on_owned_dongles 
end 

那愉快地通過。因爲它是一個協會,你可能可以在其上find()件事:

test "getting licences on owned dongles and then filtering further" do 
    org = organisations(:some_other_corp) 
    conditions = { :owner_organisation_id => nil } 
    assert_equal [licences(:licence_4)], 
    org.licences_on_owned_dongles.find(:all, :conditions => conditions) 
end 

但是這給:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: dongles.organisation_id: SELECT "licences".* FROM "licences" WHERE "licences"."parent_licence_id" IS NULL AND (("dongles".organisation_id = 72179513)) AND ("licences".parent_licence_id = 747059259) 
test/unit/organisation_test.rb:123:in `test_getting_licences_on_owned_dongles_and_then_filtering_further' 

事實上,當你打電話是find(:all)這甚至發生。這不僅僅是SQLite,因爲我在MySQL的生產(oops)中注意到了這一點。

所以我不知道。進一步調查真的很神祕。我可能會將它擱置爲「Rails無法在關聯中查找()」,請使用塊來過濾它並將其保留在此處。但我想把它拿出來,以防萬一有更好的選擇。 (實際上,如果你看看Rails生成的查詢,它是完全無稽之談,它以某種方式結束了生成一個查詢,其中某些東西必須爲NULL,並且同時等於一個值。 ,這將返回0行。)

回答

1

不要在Rails 3應用程序中使用find。

org.licences_on_owned_dongles.find(:all, :conditions => conditions) 

應該

org.licences_on_owned_dongles.where(conditions) 

編輯:它here閱讀起來。

+0

有趣。這個應用程序不是用Rails3編寫的,當我升級時,沒有任何有關這種棄用的警告...切換到where()也會盲目打破現有測試。 – Trejkaz

+1

測試期望Array的一個實例。如果您調用數組方法,.where將像數組一樣工作,但它不是數組。這是一個ActiveRecord ::關係。有趣的一點它在那裏做的魔術。嘗試添加.to_a到最後。 – charredUtensil

+0

我發現測試失敗是由於這是自2009年以來的另一個錯誤的副作用。http://stackoverflow.com/questions/1778374/否則,切換查找到此工作的位置。什麼*糟糕的是,Rails沒有不贊成find方法,而只是默默地打破了它。 GJ。 (順便說一下,如果左邊是一個數組,而右邊是一個關聯或結果集,則不需要to_a。assert_equal,Rails就好像那樣) – Trejkaz

0

我認爲你正在尋找.where

org.licenses_on_owned_dongles.where(conditions) 
相關問題