imrichardcole
imrichardcole

Reputation: 4685

Select box with text override

I have a simple form with the following:

<%= select_tag(:location_select, options_for_select(@locations)) %>
<%= text_field_tag(:location_text) %>

What is the cleanest way in the controller to accept the value provided by the select box if specified, otherwise falling back to the text box if not?

If somehow both are selected, the select box should take precedence.

Upvotes: 0

Views: 26

Answers (1)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

The cleanest way is creating validations in your model and next in controller something like this:

@location = Location.new(locations_params)

if @location.save # if your model accept params of new object
  redirect_to something_path # if you have action index in locations controller wil be: redirect_to locations_path
else
  render 'your_form_name' # if you have your form in 'new' action will be render 'new'
end

example of validates in your model:

class Location < ApplicationRecord
  validates :something_field, presence: true
end

more about validates

Upvotes: 1

Related Questions