option_groups_from_collection_for_select特定方法组 [英] option_groups_from_collection_for_select specific method group
问题描述
我想在ActiveAdmin中创建一个动态选择表单。
假设一个用户有多个订单。每个订单都有一个属性pay(布尔值)。
选择用户后,下一个选择就是该用户的订单付款。
I want to make a dynamic select form into ActiveAdmin. Let say a User has multiple Orders. And each Order has an attribute pay (boolean). After selecting the User the next seleciton is the order pay by this user.
option_groups_from_collection_for_select(User.order(:email), :orders, :email, :id, :name)
但是我不明白如何只显示已支付的订单。
But i don't get how to display only the payed orders.
推荐答案
您可以在 User $上定义方法c $ c>模型,它将替换您传入的
:orders
参数。此方法应返回 orders
You can define a method on the User
model that will replace the :orders
argument you're passing in. This method should return the orders
that are payed.
尝试使用关联声明(这将为您添加方法):
Try using an association declaration (this will add the method for you):
class User < ActiveRecord::Base
has_many :orders
has_many :paid_orders, class_name: 'Order', -> { where pay: true }
end
现在您的用户
实例将具有 paid_orders
方法,该方法返回 orders
的 pay
属性为 true
。
Now your user
instances will have a paid_orders
method that returns orders
where their pay
attribute is true
.
现在将表单助手更改为:
Now change your form helper to:
option_groups_from_collection_for_select(User.order(:email), :paid_orders, :email, :id, :name)
应该这样做。
这里的想法是:paid_orders
参数是 User
实例上方法的名称。您可以自由定义任何方法,甚至可以手动定义:
The idea here is that the :paid_orders
argument is the name of a method on an instance of User
. You are free to define any method you'd like, even manually as so:
class User < ActiveRecord::Base
has_many :orders
def paid_orders
orders.where pay: true
end
end
这篇关于option_groups_from_collection_for_select特定方法组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!