【问题标题】:Advanced search queries in Rails 3.1Rails 3.1 中的高级搜索查询
【发布时间】:2012-02-08 09:40:06
【问题描述】:

我想对任务模型执行高级查询(简化版:

class Task
    belongs_to :user_task
    belongs_to :customer
end

class UserTask
    has_many :tasks
    belongs_to: :user
    attr_accessible :date
end

class Customer
    has_many :tasks
end

我要构建的是具有以下字段的 de Task 模型的搜索表单:

  • from_date(日期字段):对应UserTask 之后 from_date
    的所有任务
  • to_date(日期字段):对应UserTask的所有任务之前 to_date
  • customers (collection as checkbox):对应客户的所有任务都包含在客户选择中。

我创建了一个用于保存搜索的 TaskSearch 资源,并且可以想象一个大而丑陋的 SQL 字符串来查询数据库,但我不确定这是不是最好的方法。

哪种是 ActiveRecord 方法?

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 search activerecord


    【解决方案1】:
    class Task
      belongs_to :user_task
      belongs_to :customer
    
      scope :from_date, lambda { |date| joins(:user_task).where("user_tasks.date > ?", date) }
      scope :to_date, lambda { |date| joins(:user_task).where("user_tasks.date < ?", date) }
      scope :with_customers, lambda { |customer_ids| joins(:user_task).where("user_tasks.user_id IN (?)", customer_ids) }
    end
    

    希望这会奏效。问题是,当我们加入表格时,您可能会为同一任务获得多个结果。您可能需要在 select() 方法中添加一个 distinct 子句,如下所示:

    select("DISTINCT tasks.*")
    

    【讨论】:

    • 非常感谢。你确定它会重复任务吗?我认为不会。
    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 2015-03-02
    • 1970-01-01
    • 2018-10-21
    • 2015-06-09
    • 2018-11-05
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多