简体   繁体   中英

add scope to form select in active_admin

I have a select field in an active_admin form which is an associated activerecord relation Travel and I would only like the travels to appear that have a status = "active" . Any idea how I can create a scope for this to be used only on the active record form?

As you can see on README , ActiveAdmin uses Formtastic to build forms. In Formtastic docs , you can see, under Usage title, how to work with collections.

So, in your Travel model you need a scope (or maybe, a class method returning an ActiveRecord::Relation )

class Travel < ActiveRecord::Base
  scope :actives, where(status: 'active')
end

Then in your ActiveAdmin form you can use that scope on :collection option

form do |f|
  f.inputs "a nice title" do
    f.input :travel_id, as: :select, collection: Travel.actives
  end
end

Maybe you will need to format the scope results. Doing something like this:

Travel.actives.map{|t| [t.name,t.id]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM