2013-02-15 62 views
2

我有一个简单的层次结构的rails 3.2应用程序:用户有很多客户端,客户端有很多发票。在范围内访问父项

我希望用户只能通过做Client.by_user(current_user)Invoice.by_user(current_user)来查看他们自己的客户和使用范围的发票。对于客户来说,我有这个,它工作得很好:但

scope :by_user, lambda { |user| where(user_id: user.id) } 

,如果我尝试在同一发票

scope :by_user, lambda { |user| where(client.user_id => user.id) } 

失败的话,告诉我undefined local variable or method 'client'

我在做什么错?我不想将user_ids添加到发票中。

+2

为什么不只是使用'current_user.clients'和'current_user.invoices'? (编辑:假设'User''has_many:invoices,:through =>:clients') – gregates 2013-02-15 20:44:13

+0

我试过了,但它没有识别'invoice.user'。我必须将user_id添加到发票表中吗? – weltschmerz 2013-02-15 20:48:04

+0

你不应该。您可以在发票''belongs_to:user,:through =>:client''处做反向关系。 – gregates 2013-02-15 20:50:05

回答

2

由于@gregates在评论中说,更好地为您定义用户协会,客户&发票模型,然后使用user.clientsuser.invoicesinvoice.user等:

class User < ActiveRecord::Base 
    has_many :clients 
    has_many :invoices, through: :clients 
end 

class Client < ActiveRecord::Base 
    belongs_to :user 
    has_many :invoices 
end 

class Invoice < ActiveRecord::Base 
    belongs_to :client 
    has_one :user, through: :client 
end 

但是,如果你喜欢的想法与范围,您应该将客户表加入您的范围内的发票:

class Invoice < ActiveRecord::Base 
    ... 
    scope :by_user, lambda { |user| joins(:client).where("clients.user_id = ?", user.id) } 
    ... 
end 
+0

'Invoice'模型中的'belongs_to:user',虽然需要'user_id'外键,不是吗?你需要'通过::客户'? – gregates 2013-02-15 21:05:44

+0

@gregates,我可以在[api文档](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to)中看到,belongs_to没有:through选项。 – Hck 2013-02-15 21:10:32

+0

我已经实现了上述功能,但在创建属于客户和用户的发票后,'invoice.user'给了我'nil' - 怎么回事? – weltschmerz 2013-02-15 21:12:40