Rails has_many和动态条件子句

时间:2015-04-14 09:53:30

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

我试图创建两个模型之间有很多关联,我需要一个动态条件来实现这个目的:

class User
    has_many :all_cars, ->(user) {where("cars.owner1_id=? OR cars.owner2_id=?", user.id, user.id)}, class_name: "Car"
end

我希望has_many关联生成如下内容:

SELECT "cars".* FROM "cars" WHERE (cars.owner1_id=1 OR c.owner2_id=1)

但改为使用rails创建:

SELECT "cars".* FROM "cars" WHERE "cars"."owner_id" = ? AND (cars.owner1_id=1 OR cars.owner2_id=1)

因为字段owner_id不存在,显然会引发错误。

我也试过

class User
    has_many :all_cars, ->(user) {where("cars.owner2_id=?", user.id, user.id)}, class_name: "Car", foreign_key: "owner1_id"
end

生成

SELECT "cars".* FROM "cars" WHERE "cars"."owner1_id" = 1 AND (cars.owner2_id=1)

但我需要使用OR代替AND

在使用动态条件时,如何使用覆盖WHERE子句的块而不是添加到现有块?

感谢

1 个答案:

答案 0 :(得分:0)

请勿使用.has_many,而是定义一个简单的方法:

class User < ActiveRecord::Base
  def all_cars
    Car.where("cars.owner1_id = ? OR cars.owner2_id = ?", id, id)
  end
end