Ruby on Rails Country/State Select Enigma

好久不见. 提交于 2019-11-30 09:47:54

It looks like you're assuming that the @person variable is still available from your original action. This could be set up by a filter for the current person but you don't show that in your question.

If you do need to lookup the @person again you'll have to pass the id through in your remote_function I think.

Ryan Bates has a Railscast that shows how to select a category for a product or create a new category by typing the name. It sounds like a similar scenario to what you have, so you might want to check it out: Create Model Through Text Field.

Kevin

This took me a full day to figure out something that would at least "work". I am also using Carmen and also messing with the select tag in a form_for model form (actually, fields_for nested within forms_for...which adds additional complications).

I would think there is a better solution but this worked for me. The select needs to be referenced by the form but the options don't. Thus, first time through, I use the Carmen state_select method which populates the select tag correctly and all the nested options tags. The second time through, I just replace the options. Take a look:

In the view, I chose to use an observe_field method since I do other things besides update the states (some other localization changes) but this should work for remote_function and others, too:

<%= address_form.country_select :country, {:prompt => "--Select One--"} %>

Don't be confused by the id (user_address_attributes_country) it is just my silly forms_for/fields_for implementation)

<%= observe_field :user_address_attributes_country, :url => { :action => :changecountry }, :with => 'new_country' %>

<%= address_form.state_select :state, @user.address.country, {:prompt => "--Select One--"}, :style => 'width: 90px' %>

Then in my controller, it just looks like this:

def changecountry
  c = params[:new_country]

  respond_to do |format|
    format.html
    format.js {
      render :update do |page|
        page['user_address_attributes_state'].innerHTML = \
          "<option>--Select One--</option>" + state_options_for_select(nil, c)
      end
    }
  end
end

Note: state_options_for_select is also from Carmen. I could not get it to work unless I put it inside the respond_to block where I guess the view helpers are available. Also, I hard code user_address_attributes_state which is my nested id generated from the form_for/fields_for address_form.state_select rendering call in the view.

I hope this helps. If anyone can do it better, believe me, I'm all ears. I'll change the design in time...but needed something that just worked today and this was the best I could figure out in a limited time.

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