alybadawy
alybadawy

Reputation: 529

Active Admin: Nested "select" input based on another select

I am working on a rails application that I building Active Admin over to manipulate the data. I have the following models for a car dealership:

class Make < ActiveRecord::Base
    has_many :models
end

class Model < ActiveRecord::Base
    belongs_to :make
    has_many   :cars
end  

class Car < ActiveRecord::Base
    belongs_to :model

    def make
        self.model.make
    end
end

I am trying to adjust the form in the ActiveAdmin "Car" model, so that instead of choosing the model from a big list of all available models, I should be able to narrow down the model by selecting the "make" and then selecting the model based on that make.

currently, I have this:

ActiveAdmin.register Car do

    controller do
        def permitted_params
            params.permit!
        end
    end

    form :html => { :multipart => true } do |f|
        f.inputs "Project Details" do |c|
            f.input :vin
            f.input :year
        end
        f.inputs "Make and model" do
            f.input :maker, :as => :select, :collection => Make.all, :include_blank => false
            f.input :model, :as => :select, :collection => Model.where(make_id: 1), :include_blank => false, :selected => (car.model.id if !car.model.nil?)
        end
    end
end

This works fine, and the models listed in the "Model" dropdown list are the ones that have a make_id = 1, as I coded. I would like the models to reflect the selected "maker". and a probably a button that updates the models list based on the make.

How can I do this?

Upvotes: 1

Views: 2974

Answers (2)

Abhilash M A
Abhilash M A

Reputation: 564

I have integrated the same functionality to one of my project. I have uploaded it to the following github repo:

https://github.com/abhidsm/dependent-select

Hope you are looking for the same :)

Upvotes: 2

seanlinsley
seanlinsley

Reputation: 3205

There isn't anything like this currently built into Active Admin, though there is a ticket for it.

You can pretty simply implement this on your own, though. Something like:

select1 = fieldset.find 'select:first' # Companies
select2 = fieldset.find 'select:last'  # Users
select1.change ->
  $.get '/admin/users.json', q: {company_id_eq: $(@).val()}, (data)->
    select2.html data.map (u)-> "<option value='#{u.id}'>#{u.name}</option>"

Upvotes: 2

Related Questions