请帮我简化这个简单的Ruby on Rails功能

时间:2012-02-26 16:59:34

标签: ruby-on-rails ruby

有人可以告诉我如何简化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

我真的无法理解这一点。感谢您的任何意见!

2 个答案:

答案 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