Question

I'm new to Rails and am fixing a Rails 2 site. I have a form that lets the user add information for the starting location (:start) EITHER with an input OR with a dropdown field. However, I have found that when I include both options, only the dropdown (which comes last) submits data, while the input is ignored. What's the right way to include both options?

MY VIEW

    <% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
    <%= f.error_messages %>
    <p>Enter a street address, city, and state:
    <%= f.text_field :start, {:id=>"startinput", :size=>50}%></p>
    <p>Or, select a location from the list:
    <%= f.select :start, options_for_select(@itinerary.locations), {:include_blank => true }, {:id=>"startdrop"} %>      

    <input type="submit" id="savethismap" value="Save Map">
    <% end %>
Était-ce utile?

La solution

One way to achieve this is by using virtual attributes. Since both fields map to same attribute, you are going to have to pick which one to use.

# app/models/newsavedmap.rb
class Newsavedmap < ActiveRecord::Base
  ...
  attr_accessible :start_text, :start_select
  ...

  def start_text=(value)
    @start_text = value if value
    prepare_start
  end

  def start_select=(value)
    @start_select = value if value
    prepare_start
  end

  # start_text will fall back to self.start if @start_text is not set
  def start_text
    @start_text || self.start
  end

  # start_select will fall back to self.start if @start_select is not set
  def start_select
    @start_select || self.start
  end

private 
  def prepare_start
    # Pick one of the following or use however you see fit.
    self.start = start_text if start_text
    self.start = start_select if start_select
  end
end

Then your form needs to use the virtual attributes:

<%= f.text_field :start_text, {:id=>"startinput", :size=>50}%></p>
<p>Or, select a location from the list:
<%= f.select :start_select, options_for_select(@itinerary.locations), {:include_blank => true }, {:id=>"startdrop"} %>

Other options are:

  1. Use text_field as the primary and update it's value with selected option if user selects an option.
  2. Add a hidden field in your form and use JavaScript to update the hidden field's value when text_field text gets updated or select option changes
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top