GeorgesLeYeti
GeorgesLeYeti

Reputation: 199

option_groups_from_collection_for_select specific method group

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.

Upvotes: 3

Views: 1127

Answers (1)

DiegoSalazar
DiegoSalazar

Reputation: 13521

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

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)

That should do it.

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

Upvotes: 3

Related Questions