【问题标题】:searching records in rails include belongs_to or has_many在rails中搜索记录包括belongs_to或has_many
【发布时间】:2013-06-18 18:12:56
【问题描述】:

我有两个模型,产品和生产者。一个生产者可以有许多产品,一个产品属于一个生产者。 我现在正试图从这样的搜索查询中获取所有记录:

@products = Product.where("name like ? OR product.producer.name like ?", "%#{params[:q]}%", "%#{params[:q]}%")

这应该返回 product.name 或 product.producer.name 与搜索字符串类似的所有产品。有短轨吗?

【问题讨论】:

  • 是的。如果你需要使用喜欢你应该阅读一些关于全文搜索。

标签: ruby-on-rails where rails-activerecord has-many belongs-to


【解决方案1】:

您可以执行以下操作:

Product.includes(:producer)
        .where('products.name LIKE ? OR producers.name LIKE ?', "%#{params[:q]}%", "%#{params[:q]}%")

你可以用它做一个范围:

class Product < ActiveRecord::Base

  scope :with_name_like, lambda { |name| 
            includes(:producer).where('products.name LIKE ? OR producers.name LIKE ?', "%#{name}%", "%#{name}%") 
  }

并像这样使用它:

@products = Product.with_name_like('Chair')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2013-07-27
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多