有人可以告诉我如何简化Invoice
模型中的以下功能吗?它应返回与特定Invoices
相关的所有Client
(均通过Projects
表格连接)。
def self.search_by_client_id(client_id)
if client_id
projects = Project.where(:client_id => client_id)
Invoice.where(:project_id => projects)
else
scoped
end
end
我真的无法理解这一点。感谢您的任何意见!
答案 0 :(得分:3)
这似乎是范围的绝佳机会!
scope :client, lambda{|id| includes(:projects).where('projects.client_id = ?', id)}
Invoice.client(4).all # returns all invoices for the client with the specified ID.
答案 1 :(得分:1)
如果我理解你的问题,你应该能够使用ActiveRecord关联来做到这一点:
class Client < ActiveRecord::Base
has_many :projects
has_many :invoices, :through => :project
end
class Project < ActiveRecord::Base
has_many :invoices
belongs_to :client
end
class Invoice < ActiveRecord::Base
belongs_to :project
has_one :client, :through => :project
end
然后,所有Invoices
与特定Client
:
@client.invoices
获取与特定发票相关联的Client
:
@invoice.client