Can*_*yer 0 ruby ruby-on-rails ruby-on-rails-5
我觉得这很简单,但我发现似乎没有任何效果。我正在使用带有 Rails 5 的 PostgreSQL 数据库。我需要运行一个查询来查找在名称列中包含文本字符串的所有产品或在关联模型中找到相同字符串的所有产品。这是我的模型结构。
class NormalBrand < ApplicationRecord
has_many :normal_models
end
class NormalModel < ApplicationRecord
belongs_to :normal_brand
has_many :products
end
class Product < ApplicationRecord
belongs_to :normal_model
end
Run Code Online (Sandbox Code Playgroud)
每个模型都有一个名为“名称”的字段。我试图在我的 Products 控制器中创建一个查询,以查找在 3 个模型“名称”列中的任何一个中找到文本字符串的所有产品。像这样的东西...
@products = Product.where("name like lower(?)", "%#{value}%").or.where("normal_model.name like lower(?)", "%#{value}%").or.where("normal_model.normal_brand.name like lower(?)", "%#{value}%")
Run Code Online (Sandbox Code Playgroud)
我知道上面的查询是完全错误的,我应该有某种 joins 语句,但这就是我需要帮助的地方。提前致谢。
加入normal_model和normal_brand,然后你可以在所有三个表的查询
@products =
Product
.joins(normal_model: :normal_brand)
.where("products.name like lower(?)", "%#{value}%")
.or.where("normal_models.name like lower(?)", "%#{value}%")
.or.where("normal_brands.name like lower(?)", "%#{value}%")
Run Code Online (Sandbox Code Playgroud)
或者干脆在一个原始的地方
@products =
Product
.joins(normal_model: :normal_brand)
.where("products.name LIKE lower(:term) OR
normal_models.name LIKE lower(:term) OR
normal_brands.name LIKE lower(:term)", term: "'%#{value}%'")
Run Code Online (Sandbox Code Playgroud)