Active Admin - refresh second drop down based on first drop down, Ruby on Rails

Astha picture Astha · Mar 6, 2012 · Viewed 10.8k times · Source

I am using Active Admin Gem on Ruby on Rails. I have a form in which i have selected category and sub category and then accordingly i have to fill the data. So i created two tables in sqlite added in active admin resouce.

Every thing is working fine but the drop down of sub category is not getting filtered based on the category choosen.

I am new to Ruby and RoR too. I don't know how to refresh dropdown of the subcategory after selecting category.

I know i can do it from AJAX and javascript but i dont know where to code for that?

Also, is there any specific filter avaliable in Active Admin which will make it happen without ajax or javascript.

Any ideas or help will be highly appreciated.

Answer

okliv picture okliv · Jul 22, 2012

i don't know if there is any specific filter avaliable in Active Admin, but i solved it in this 3-steps way (assuming category - is a house, subcategory - is a flat):

1-st step: define helper containing ajax request

(of course, you have to predefine path in routes.rb)

#application_helper.rb
def remote_request(type, path, params={}, target_tag_id)
  "$.#{type}('#{path}',
             {#{params.collect { |p| "#{p[0]}: #{p[1]}" }.join(", ")}},
             function(data) {$('##{target_tag_id}').html(data);}
   );"
end

2-nd step: add this method for :onchange action

#admin/inhabitants.rb (DSL with formtastic)

form do |f|
  f.inputs do
  #...
    f.input :house, :input_html => {
        :onchange => remote_request(:post, :change_flats, {:house_id=>"$('#house_id').val()"}, :flat_id)
    }
    f.input :flat
  #...
  end
end

3-rd step: render result of filtering

(you can render partial instead of :text, I decided leave it in one activeadmin resource file )

controller do
  def change_flats
    @flats = House.find_by_id(params[:house_id]).try(:flats)
    render :text=>view_context.options_from_collection_for_select(@flats, :id, :flat_number)
  end
end