2013-02-15 71 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