使用class_name的ActiveRecord范围

时间:2015-03-10 15:05:57

标签: ruby-on-rails activerecord ruby-on-rails-3.2 rails-activerecord

我有一个模型可以保留2个用户"用户"和"工人"。

create_table "action_logs", :force => true do |t|
  t.integer  "user_id"
  t.integer  "worker_id"
  t.string   "text_log"
end

class ActionLog < ActiveRecord::Base
  belongs_to :user
  belongs_to :worker, :class_name => 'User'
end

现在,我想用&#34; user&#34;写一个范围。和&#34;工人&#34;在这个模型上。

scope :not_inhouse, -> { 
  includes(:user).where( "users.inhouse = ?", false).
  includes(:worker).where( "workers.inhouse = ?", false) 
}

但它没有用。

ActiveRecord::StatementInvalid: 
  SQLite3::SQLException: no such column: workers.inhouse: 
  SELECT COUNT(DISTINCT "action_logs"."id") FROM "action_logs" LEFT OUTER JOIN "users" ON "users"."id" = "action_logs"."user_id" LEFT OUTER JOIN "users" "workers_action_logs" ON "workers_action_logs"."id" = "action_logs"."worker_id" WHERE (users.inhouse = 'f') AND (workers.inhouse = 'f')

似乎ActiveRecord没有像我预期的那样处理class_name。 有没有办法使用class_name编写范围?

1 个答案:

答案 0 :(得分:0)

感谢您的评论。现在我理解了2分。

  • 包含和加入之间的差异。
  • ActiveRecords名称已加入表名,与class_name无关。

所以我可以像这样编写范围:

scope :not_inhouse, -> { 
  joins(:user).where( "users.inhouse = ?", false).
  joins(:worker).where( "workers_action_logs.inhouse = ?", false)
}

scope :not_inhouse, -> { 
  joins(:user).where( "users.inhouse = ?", false).
  joins('INNER JOIN "users" "workers" ON workers.id = action_logs.worker_id').
  where( "workers.inhouse = ?", false)
}