如何在Rails 4中将参数传递给has_many关联范围? [英] How do I pass an argument to a has_many association scope in Rails 4?

查看:74
本文介绍了如何在Rails 4中将参数传递给has_many关联范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 4使您可以像这样限制has_many关系的范围:

Rails 4 lets you scope a has_many relationship like so:

class Customer < ActiveRecord::Base
  has_many :orders, -> { where processed: true }
end

因此,只要您执行customer.orders,您都只会得到已处理的订单.

So anytime you do customer.orders you only get processed orders.

但是,如果我需要使where条件动态化怎么办?如何将参数传递给范围lambda?

But what if I need to make the where condition dynamic? How can I pass an argument to the scope lambda?

例如,我只希望针对多租户环境中客户当前登录的帐户显示订单.

For instance, I only want orders to show up for the account the customer is currently logged into in a multi-tenant environment.

这就是我所拥有的:

class Customer < ActiveRecord::Base
  has_many :orders, (account) { where(:account_id => account.id) }
end

但是,如何在我的控制者或视图中传递正确的帐户?使用上面的代码后,我就可以这样做:

But how, in my controller or view, do I pass the right account? With the code above in place when I do:

customers.orders

我似乎是任意获得ID为1的帐户的所有订单.

I get all orders for account with an id of 1, seemingly arbitrarily.

推荐答案

方法是为has_many范围定义其他扩展选择器:

The way is to define additional extending selector to has_many scope:

class Customer < ActiveRecord::Base
   has_many :orders do
      def by_account(account)
         # use `self` here to access to current `Customer` record
         where(:account_id => account.id)
      end
   end
end

customers.orders.by_account(account)

Rails Association 头中的Association Extension中描述了该方法. a>页面.

The approach is described in Association Extension head in Rails Association page.

要访问嵌套方法中的Customer记录,您只需访问self对象,该对象应具有当前Customer记录的值.

To access the Customer record in the nested method you just can access self object, it should have the value of current Customer record.

Sinse of rails(大约5.1),您可以将模型范围与相同类型的其他模型 has_many 范围合并,例如,您可以按以下方式编写相同的代码:两种模式:

Sinse of rails (about 5.1) you are able to merge models scope with the othe model has_many scope of the same type, for example, you are able to write the same code as follows in the two models:

class Customer < ApplicationRecord
   has_many :orders
end

class Order < ApplicationRecord
   scope :by_account, ->(account) { where(account_id: account.id) }
end

customers.orders.by_account(account)

这篇关于如何在Rails 4中将参数传递给has_many关联范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆