我有一些像这样的模型类:
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行。)
答案 0 :(得分:1)
不要在Rails 3应用程序中使用find。
org.licences_on_owned_dongles.find(:all, :conditions => conditions)
应该是
org.licences_on_owned_dongles.where(conditions)
修改:阅读here。
答案 1 :(得分:0)
我认为你正在寻找.where
:
org.licenses_on_owned_dongles.where(conditions)