问题
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 %>
回答1:
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:
- Use text_field as the primary and update it's value with selected option if user selects an option.
- 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
来源:https://stackoverflow.com/questions/18580849/using-two-separate-fields-for-the-same-parameter-in-a-rails-form-handler