Not setting anything in Rails' collection_select - ruby-on-rails

I have a Rails 2.3 web application that uses the collection_select helper with :multiple => true to handle a habtm relationship. This is working fine to set one or multiple values, however I have not figured out how to allow to REMOVE all selections.
Code:
<%= f.collection_select :category_ids, Category.find(:all), :id, :name,
{ :selected => #entry.category_ids },
{ :multiple => true, :name => 'entry[category_ids][]' }
%>
Once the user has ever set a category for an entry, how would I go about allowing it to be removed, so that this entry has no category? Is this possible with collection_select or would I need to add a checkbox to handle this specially?
P.S: I already tried with :prompt, :include_blank and :allow_blank, but as far as I could see neither of them did anything.

In your controller's update action, put in the following line:
params[:entry][:category_ids] ||= []
before the call to Entry.find.

Related

How to use :selected with grouped_collection_select

Is it possible to somehow use the :selected option that you'd use on a normal select view helper with the grouped_collection_select function? I'd like to set the value that gets pre-selected in my list. I've tried passing in :selected as an option with no luck!
Here's some code snippts of my tests:
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, { :include_blank => true, :selected => 5 }
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, :include_blank => true, :selected => 5
Neither version works. No selected is set. I'm using this to set a value for a nested model. I'm using the railscasts dynamic select list methods: http://railscasts.com/episodes/88-dynamic-select-menus-revised
I couldn't get formtastic to play nicely with the group selects so I had to do it by hand but I don't keep this value selected when a user fails validations. I'd like to keep this set when they fix validation errors.
I just ran across the same problem and solved it using the option_groups_from_collection_for_select helper and the select helper documented at: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html.
The first step is to create the grouped options. Taking your example, it should look like:
<% options = option_groups_from_collection_for_select(Trade.order(:name).all,
:subscription_plans, :name, :id, :display_name, 5) %>
Then I created the select object like:
<%= select('user[subscription_attributes]', :subscription_plan_id, options,
include_blank: true) %>
You could write it all out in one line, I just broke out the options into a separate variable to illustrate the two different methods.
Maybe too late, but the API documentation of grouped_collection_select states:
'The value returned from calling method on the instance object will be selected.'
So, you don't even have to specify a :selected option, since Rails will automatically select based on the current value of your attribute.
If subscription_plan_id has value 5, then that's what will be selected.
If that's supposed to be a default value, then you can set it with an after_initialize in your model.
Actually you need to send in options include_blank for example
<%= grouped_collection_select :id, model.all, options = {:include_blank => 'Selecione'}%>

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 } ) %>

How to set a field read only in rails 3.1.0 views?

My question is how to set a field in rails form read only. The following is a selection box in quotes controller. Users are not allowed to change the selection.
<% #quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :selected => t.id %>
<% end %>
The app uses simple_form. Thanks so much.
I've encountered a similar problem, thankfully, there is a simple resolution.
The basic issue is that if you use :disabled => true with simple_form you will not see that value back in the controller. When you pass an object from HTML form to later bind it to the model - you need all of those attributes. The :disabled => true however does not pass any such attribute.
The solution to this is to use :readonly => true - it will protect the field from user entry and it will still pass the param value back to the controller so you can bind everything to your model.
Good luck.
See https://github.com/plataformatec/simple_form/pull/367
I believe you'd just pass in :disabled => true. It's been my experience that options 'just work' with simple_form. So in your case:
<% #quote.test_items.each do |t| %>
<%= f.association :test_items, :label => false, :disabled => true, :selected => t.id %>
<% end %>
From the simple_form github repo:
It is also possible to give the :disabled option to SimpleForm, and it'll automatically mark the wrapper as disabled with a css class, so you can style labels, hints and other components inside the wrapper as well.
Yes, what #gk0r said, as it is documented here:
NOTE: The HTML options disabled, readonly, and multiple can all be treated as booleans. So specifying :disabled => true will give disabled="disabled".
*disabled will have slightly different behavior than readonly.
The top answers above are all wrong.
disabled attribute has a different behaviour than readonly.
read and compare them:
http://www.w3schools.com/tags/att_input_disabled.asp
Tip: Disabled elements in a form will not be submitted.
http://www.w3schools.com/tags/att_input_readonly.asp
The right answer is to use
:readonly => true
something like this:
<%= f.association :test_items, :label => false, :readonly => true, :selected => t.id %>
It's not clear to me if the association method accepts HTML options or not, but if it does, you can pass disabled: 'disable' to make it read-only with a fixed value.
I think you might be able to choose the fixed value by passing association as block, as shown in the association docs:
f.association :company do |c|
c.input :name, selected: 'selection'
c.input :type
end
As to whether or not the entire list can be read-only and still drop-down, the only solutions I see from google involve JS, for example:
http://techeyes.blogspot.com/2007/11/making-html-select-readonly.html

Rails, collection_select - remembering values with :selected after form submitted

(Using Rails 2.3.5 on an internal work server with no choice of versions, and I'm pretty new)
I'm building a search form where I need to provide a list of directories to a user so they can select which one(s) to search against. I'm trying to figure out how to get the selected values of a collection_select to remain after the form is submitted.
Say the user selected 3 directories from the collection_select, the id's of those directories would look like this in the params:
directory: !map:HashWithIndifferentAccess
id:
- "2"
- "4"
- "6"
I know that you can manually specify multiple selected items:
<%= collection_select :directory, :id, #directories, :id, :name,
{:selected => [2,4,6]}, {:size => 5, :multiple => true} %>
I've also played around a bit and was able to us "to_i" against a single value in the params hash:
<%= collection_select :directory, :id, #directories, :id, :name,
{:selected => params[:directory][:id][0].to_i}, {:size => 5, :multiple => true} %>
What I can't figure out is how to use all of the values of the :directory params at the same time so what the user selected remains after the form is submitted. Thanks for any help.
I'm not precisely sure what you're asking, but if you're trying to get the array of strings in params[:directory][:id] as an array of integers, all you need is
params[:directory][:id].map{|id|id.to_i}

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