在Rails 3.2.21应用程序中,我有这些简单的类:
class Country < ActiveRecord::Base
default_scope -> do
where("country_translations.locale = ?", I18n.locale).
order("country_translations.name").includes(:translations)
end
has_many :regions
has_many :cities
has_many :translations
attr_accessible :name, :city_ids
active_admin_translates :name
end
class Region < ActiveRecord::Base
default_scope -> do
where("region_translations.locale = ?", I18n.locale).
order("region_translations.name").includes(:translations)
end
belongs_to :country
has_many :cities
attr_accessible :country, :name, :country_id, :city_ids
active_admin_translates :name
end
当我Country.first.region_ids
时,我有这个错误:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "region_translations"
LINE 1: ...regions" WHERE "regions"."country_id" = 602 AND (region_tra...
^
: SELECT "regions".id FROM "regions" WHERE "regions"."country_id" = 602 AND (region_translations.locale = 'en') ORDER BY region_translations.name
from /home/dougui/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activerecord-3.2.21/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `exec'
正如您所看到的,在SQL请求中,似乎不包括region_translations
。因此,它无法在订单条款中找到它。它似乎忽略了包含。
Country.first.regions.map(&:id)
可以运作,但这是一个糟糕的黑客攻击。
你有更好的解决方案吗?
答案 0 :(得分:1)
您应同时使用joins
和includes
。这将处理性能和错误。