Set :selected value based on variableX -or- the user submitted value if variableX is nil - ruby-on-rails

Have this select dropdown input field that is populated with state names.
I want to set the selected value to be the content of #state.id if this is not nil. If there is already a chosen option then I would like that to be selected instead.
How can this be done correctly? I tried several solution all of which fails, latest code example im using now:
= p.input :state,
:collection => ["State1","State2"]
:selected => (#state.id.to_s rescue nil) || (params[:state] rescue nil),
:id => "state",
:name => "state",
:prompt => t('forms.choose')

The problem is that the :selected option works based on two values.
The index of the element in the collection array, or
The value itself
So lets say you want the the last option to be selected, in your case you would need:
:selected => 1
or
:selected => "State2"
I hope it helps.

Related

Array returns first element blank in my Rails(3.2.11) multi-select

When I selected multiple values from select list then array returns the first value empty.
= f.select :assignedto, options_from_collection_for_select(User.all, 'name', 'name',f.object.assignedto),{}, { :multiple => true}
I tried with {:include_blank => false} and {:include_hidden => false} but this is not working for rails 3.2.11. I have many solutions to handle this empty value in the controller but I want to stop adding empty value in the array.
Properly because the second arg is 'name' instead of 'id'.
Try
options_from_collection_for_select(User.all, 'id', 'name', f.object.assignedto)

Stored value not being set to nil when user deselects all options - rails / simple_form

I have the following form input which is working, except for one small 'bug'
<%= f.input :secondary_role, :collection => UseridRole::VALUES, :include_blank => false,:label => "Secondary Role(s):", :input_html => { :class => " simple_form_bgcolour simple_form_position overide_selection_field_width", :size => 4, multiple: true }, include_hidden: false, :hint => "Hold shift to select multiple roles" %>
My user's secondary role is stored in my DB as an array:-
"secondary_role": ["moderator"]
My problem is that in cases where the user has set a secondary role, that can't be un-set by deselecting the option. Nothing happens when an option is deselected in the list and saved. The above moderator can only be removed by selecting another option. How can I make the array empty upon deselection of all?
Remove the include_hidden: false option; the hidden field is there to make this work automatically.
(Otherwise, you'll need to handle the situation manually in the controller action that receives the form submission.)
So as #matthewd pointed out, the solution was to remove the include_hidden: false option, although this introduced another issue of a blank array item being added to my roles array.
So, I added the below method to trigger before every save and remove any blank array entries:
def remove_blank_entry
secondary_role = self.secondary_role
if secondary_role.include? ""
secondary_role.delete("")
end
end

Rails Multiple Select boxes: Injecting default values from params

I currently have a multiple select box in a rails form that looks like this:
= select_tag :in_all_tags, options_from_collection_for_select(Tag.where(:project_id => #project.id), :id, :name, #in_all_tags_param), { :id => "tags", :tabindex => "3", "data-placeholder" => "Choose Tags", :multiple => "multiple" }
Where
#in_all_tags_param = params[:in_all_tags]
The problem is, #in_all_tags_param will only populate the select form with the last value from params[:in_all_tags]. So, if the url string reads in_all_tags=5&in_all_tags=8, the pre-selected value in the multiple select will only be 8.
From what I understand, the way around this is to append [] to the field name for multiple params, so that :in_all_tags becomes in_all_tags[]
BUT, when I try this, submitting the form returns:
Expected type :default in params[:in_all_tags], got Array
Any suggestions appreciated.
Cheers...
You need to add a :name element to the same hash with :multiple => true in it. So I use something similar for Genres on an app for mine and I do { :multiple => true, :name => "lesson[genre_ids][]" }. The name has to be model[attribute][].

Set Selected Value on Dropdown Based on Model Property

i have a simple dropdown like :
<%= collection_select("user_cities", "city_id", current_user.cities, :id, :name ) %>
current_user.cities is an array of the user cities. Each city has a field named "is_primary" and only one city has it set as true.
My question is, how can i make the above collection_select(or transform it if needed), so that it picks the selected option, based on City.is_primary ?
From the docs:
By default, post.person_id [in your case user_cities.city_id] is the selected option. Specify :selected => value to use a different selection or :selected => nil to leave all options unselected.
Armed with that knowledge we can pass the appropriate option to collection_select:
<%= collection_select "user_cities", "city_id", current_user.cities, :id, :name,
:selected => current_user.cities.detect(&:is_primary).id
%>
collection_select("user_cities", "city_id", current_user.cities, :id, :name,{:selected => current_user.cities.where(:is_primary => 1)})
I would start by defining a method called primary_city in your User model.
def primary_city
cities.where(:is_primary => true).first
end
Then,
<%= collection_select("user_cities", "city_id", current_user.cities, :id, :name, { :selected=> current_user.primary_city.id } ) %>

Preselect Check box with Rails Simple_form

I'm using Simple_Form with Rails 3 and it's great. I have a simple question. I can create a check box using f.input if the type is boolean behind the scenes. However, I would like it to be preselected as true.
Is there a way to do this via the view?
If you don't want to, or cannot update your migration to do 'PerfectlyNormal's answer, then you can add the following to the end of your f.input:
:input_html => { :checked => true }
So, it would become:
= f.input :some_flag, :input_html => { :checked => true }
the best way would be to set the default value in your model, something like
create_table :my_table do |t|
...
t.boolean :my_boolean, :default => true
...
end
which simple_form will pick up on, and set the checkbox to be checked by default.
A simpler way is to do it as Dave says, and just force the value to 1, but if a validation fails, and you display the form again, it will still be checked, regardless of how it looked when the form was submitted.
It Worked for me which checks only one checkbox with value of "None"
<%= f.input :notify, label: "Notification", as: :check_boxes, collection: ["None", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], :item_wrapper_class => 'inline', :checked => ["None", true] %>
I just stumbled over this post and what worked for me is similar to the latest answer - but shorter. Just initialize the Object with the wished setting:
def new
Object.new(my_boolean: true)
end
In my opinion, the rail way to do this would be to set the value of the attribute in the controller:
#some_object.some_flag = 1
This should work:
= f.input :some_flag, :input_html => { :value => '1' }
If you do the following, as in the highest rated answer (and as noted by #PerfectlyNormal) you are essentially hard-coding the state for every page load:
= f.input :some_flag, :input_html => { :checked => true } # don't do this
If you are using Rails-style server validation, this will have the unintended side effect of resetting the user's choice when validation fails.
Defaulting it in the model is ideal if the default value is static. In some cases though, the default value is driven by some business rule, so setting it at runtime is desired. For example, in my case, I wanted to default a checkbox to true, but only for certain types of organizations.
What you want is to default the value only when it is not already set, otherwise use the user-selected value. Here's how I handled this:
- is_checked = #org.is_special.nil? ? true : #org.is_special?
= f.input :some_flag, :input_html => { :checked => is_checked }
For Rails 6+, you can simply do:
<%= f.check_box :remember_me, checked: true %>

Resources