【发布时间】:2013-01-31 21:59:51
【问题描述】:
我有一个具有简单层次结构的 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 添加到发票中。
【问题讨论】:
-
为什么不直接使用
current_user.clients和current_user.invoices? (编辑:假设Userhas_many :invoices, :through => :clients) -
我试过了,但它无法识别
invoice.user。我是否必须为此将 user_id 添加到 invoices 表中? -
你不应该。您也可以在
Invoicebelongs_to :user, :through => :client处进行逆关系。 -
附注我最初的怀疑是,这也可能是您的范围出了问题——您是否在
Client和Invoice模型上设置了反向belongs_to关系?
标签: ruby-on-rails scope associations rails-activerecord