我有一个模型可以保留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编写范围?
答案 0 :(得分:0)
感谢您的评论。现在我理解了2分。
所以我可以像这样编写范围:
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)
}