私はこのようないくつかのモデルクラスを持っています:
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)
。MySQLの本番環境(おっと)でこれに気づいたので、SQLiteだけではありません。
だからわかりません。さらに調査するのは本当に神秘的すぎます。「Railsはアソシエーションでfind()を実行できない」として棚上げし、ブロックを使用してフィルタリングし、そのままにしておきます。しかし、もっと良い選択肢がある場合に備えて、私はそれを出したかったのです。
(実際、Railsが生成しているクエリを見ると、まったく意味がありません。どういうわけか、何かがNULLであり、同時に値と等しくなければならないクエリを生成することになります。クエリが機能したとしても、これは0行。)