Ruby 构建 .where 超过两个 类
Ruby build .where over two classes
我在构建 .where
以检索特定值时遇到问题。
我有这个层次结构:
-客户
--has_many 项目
---has_many 门票
我想通过客户 ID 检索所有票据作为 ActiveRecord::Relation。
我的想法是这个循环(c 是我想要门票的客户):
customer_projects = Project.where(:customer_id => c.id)
tickets = ActiveRecord::Relation.new(Ticket, anything)
customer_projects.each do |cp|
project_tickets = Ticket.where(:project_id => cp.id).where("DATE(created_at) >= ?", report.start_time).where("DATE(created_at) <= ?", report.end_time)
tickets.insert(project_tickets)
end
我既不确定在哪里写 "anything" 作为 table 参数,也不知道这是否有效。我更喜欢可以检索所有门票的 "simple" .where
。
您不需要所有这些麻烦。你有 through
方法为你做这件事。
# customer.rb
has_many :tickets, through: projects
# ticket.rb
has_many :customers, through: projects
这样,你可以做到:
@customer.tickets
@ticket.customers
我在构建 .where
以检索特定值时遇到问题。
我有这个层次结构:
-客户
--has_many 项目
---has_many 门票
我想通过客户 ID 检索所有票据作为 ActiveRecord::Relation。
我的想法是这个循环(c 是我想要门票的客户):
customer_projects = Project.where(:customer_id => c.id)
tickets = ActiveRecord::Relation.new(Ticket, anything)
customer_projects.each do |cp|
project_tickets = Ticket.where(:project_id => cp.id).where("DATE(created_at) >= ?", report.start_time).where("DATE(created_at) <= ?", report.end_time)
tickets.insert(project_tickets)
end
我既不确定在哪里写 "anything" 作为 table 参数,也不知道这是否有效。我更喜欢可以检索所有门票的 "simple" .where
。
您不需要所有这些麻烦。你有 through
方法为你做这件事。
# customer.rb
has_many :tickets, through: projects
# ticket.rb
has_many :customers, through: projects
这样,你可以做到:
@customer.tickets
@ticket.customers