Active Admin -refresh second drop down based on choice on first drop down (Rails 3.2)

风流意气都作罢 提交于 2019-12-12 13:25:58

问题


I'm having trouble implementing a form on active admin where the second dropdown (subcategory) has to adjust to the category choice on the drop down that precedes it.

Basically I want to first set a industry for a company then select among sub-industry drop down. I have created 2 models:

  • CompanySector
  • CompanySubsector

For practical reasons, I use the words 'sector' and 'subsectors' in the code.

I am trying to use @okliv suggestions on Active Admin - refresh second drop down based on first drop down, Ruby on Rails but with no success.

1- I created a route

In #routes.rb

resources :companies

  post '/change_company_subsectors' =>'company_sectors#change_company_subsectors'

2- I defined a define helper containing ajax request in Helpers/ApplicationHelper.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

3- i put in admin/company.rb this method for :onchange action

    controller do
    def change_company_subsectors
      @company_subsectors = CompanySector.find_by_id(params[:company_sector_id]).try(:company_subsectors)
      render :text=>view_context.options_from_collection_for_select(@company_subsectors, :id)
      end
    end

4- And in my active amdin form admin/company.rb, i added this in the edit form:

form do |f|

f.inputs "company" do

  f.input :company_sector_id, :input_html => { 
    :onchange => remote_request(:post, :change_company_subsectors, {:company_sector_id => "$('#company_sector_id').val()"}, :company_subsector_id)
  }
  f.input :company_subsector_id
end

But the results is very bad: I don't even see a dropdown populated with the Sectors and Subsectors possibilities.

I should see for Sectors: Leisure/Travel/Fashion... but I see nothing. And i see also nothing for SubSectors.

Shouldn't I use formtastic Collections like: :as => :select, :collection => CompanySubsector.all?

Does anyone know where I have made mistakes?


回答1:


First off I'd suggest against putting JS directly on an HTML element; it makes for much more difficult debugging later on.

Here's what I often do:

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>"""
).change()


来源:https://stackoverflow.com/questions/20034892/active-admin-refresh-second-drop-down-based-on-choice-on-first-drop-down-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!