0

我有一些这样的模型类:

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 无法在关联上执行 find()”,使用块对其进行过滤并将其保留。但我想把它拿出来,以防万一有更好的选择。

(实际上,如果您查看 Rails 正在生成的查询,那完全是胡说八道。不知何故,它最终生成了一个查询,其中必须同时为 NULL 和等于一个值。即使查询有效,这也会返回0 行。)

4

2 回答 2

1

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

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

应该

org.licences_on_owned_dongles.where(conditions)

编辑:在这里阅读它。

于 2013-02-01T00:59:21.187 回答
0

我想你正在寻找.where

org.licenses_on_owned_dongles.where(conditions)
于 2013-02-01T00:59:38.933 回答