Nic*_*nil 1 search activerecord ruby-on-rails ruby-on-rails-3
我想对Task模型执行高级查询(简化版本:
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
Run Code Online (Sandbox Code Playgroud)
我想要构建的是de Task模型的搜索表单,其中包含以下字段:
我创建了一个用于保存搜索的TaskSearch资源,可以想象一个用于查询数据库的大而丑的SQL字符串,但我不确定这是最好的方法.
哪个是ActiveRecord方法?
提前致谢.
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
Run Code Online (Sandbox Code Playgroud)
希望这会奏效.问题是,当我们加入表格时,您可能会为同一任务获得多个结果.您可能必须向select()方法添加distinct子句,如下所示:
select("DISTINCT tasks.*")
Run Code Online (Sandbox Code Playgroud)