Super simple, dumb thing, which I can't figure out for more, than an hour now:
def user_params
params.require(:user).permit(customer_ids: []) # pg array column
end
My form:
= f.select :customer_ids,
options_from_collection_for_select(customers, 'id', 'name', user.customer_ids),
{ include_blank: 'Select customer', multiple: true, size: 15 },
class: 'form-control'
And while updating user I'm getting
Unpermitted parameter: customer_ids
How the heck in the world is that possible?
Parameters: {"utf8"=>"✓", "authenticity_token"=>"oCkUEi2pNajM0ydHUH2w6iYIq5eKjfCY5ig9U2qDTXxMqECCgQ2Dn9YtqkMqXlTmLl5q/OO8x23o/P50SnmgUg==", "user"=>{"customer_ids"=>"84"}, "commit"=>"Assign selected customer to user", "id"=>"2"}
Your form isn't sending in the customer_ids parameters as an array.
"user"=>{"customer_ids"=>"84"}
This is why. It should be (notice the square brackets):
"user"=>{"customer_ids"=>"[84]"}
If you declare the param as an array, it should be posted as an array. This is likely an issue in your form.
Usually, I would use checkboxes for something like this, but this depends on your user interface. Here's something similar I have done in the past.
= f.collection_check_boxes :customers, customers, :id, :name do |cb|
= cb.label
span.pull-right = cb.check_box
Look at the collection form helpers in Rails. A multiselect should work, but I have not used one this way.
Try changing your select tag like this
= f.select(:customer_ids, customers.collect { |c| [ c.name, c.id ] },
{ prompt: "Select Customer"},
{ multiple: true, size: 5, class: 'form-control' })
Related
I'm building an app for a restaurant and I have a form where I add meals to an order and a price field gets dynamically updated depending on what dishes and how many of them you pick.
To do that I built a nested form (I think that doesn't matter anyway) which looks as follows:
.nested-fields
= f.collection_select(0, #dishes.collect{ |dish| [dish.name, :data => {:description => dish.price}]}, :name, :name, {include_blank: true}, {class: "meal-select"})
= f.select :quantity, options_for_select((1..10))
= f.text_field(:price, disabled: true)
= link_to_remove_association "X", f
The thing that bugs me is the collection_select. As you can see, I am returning an array with a name and a data-description which goes to the HTML tag. Based on the data-description, my price field gets updated.
However, I have no idea what method I should choose to extract the name of a dish. As you can see I tried 0 since name of the dish is always first in the array. I have also tried :first, :name but none of those works! The error I get is:
"NoMethodError in Orders#new
undefined method '0' for #Meal:0x007fe4eb8e26c8"
or when I use :name
undefined method `name' for ["Zupa z Krewetkami", {:data=>
{:description=>17.0}}]:Array
Naturally, it points to:
= f.collection_select(0, #dishes.collect{ |dish| [dish.name, :data => {:description => dish.price}]}, :name, :name, {include_blank: true}, {class: "meal-select"})
I don't think the problem lies in my controller but, I'll show it just in case:
def new
#dishes = Dish.all
#order = current_user.orders.build
end
I tried looking for an answer here but as you can see the problem has not been solved and it was slightly different than mine.
To sum up - my question is what method I should use to extract name of the dish from my array in collection_select. Thanks!
Here is how you can use collection_select
...
= f.collection_select :meal_select, #dishes, :name, :price, {include_blank: true}, {class: "meal-select"}
...
For more details see the docs.
Use below approach
options_for_select( [['First', 1, {:'data-price' => 20}],
['Second', 2, {:'data-price' => 30}]] )
= f.select :meal_select, options_for_select(#dishes.collect{ |dish| [dish.name, dish.price,{'data-description' => dish.price}]}), :class => 'meal-select'
Select Field:
<%= f.select :study_material_type, StudyMaterial::TYPES.map{|v| [v,v]}, selected: f.object.try(:study_material_type) , required: true,include_blank: "Please select a Study Material"%>
I want to validate the presence of :study_material_type select field. How can I do this?
Select takes in 5+ options while required validation is a html_option
i.e
select(object, method, choices = nil, options = {}, html_options = {}, &block)
put the html arguments in { } as a html_options. This should work for you.
<%= f.select :study_material_type, StudyMaterial::TYPES.map{|v| [v,v]}, {include_blank: "Please select a Study Material"}, {required: true } %>
Here is a good material for you to understand better.
I have a form for projectuser data, but when I edit the projectuser, the selected projectuser stays empty, what is going wrong? This is the code:
= f.select :user_id, options_for_select(#users.map{ |u| [u.full_name, u.id] }, selected: #projectuser.full_name), include_blank: true
The documentation states:
(...)
options_for_select(container, selected = nil) public
(...)
(million examples)
So you shouldn't pass selected: something, but just something. Also, this something needs to be selected value, not text:
= f.select :user_id, options_for_select(#users.pluck(:name, :id), #projectuser.id), include_blank: true
following your answer I wrote something like this.
f.select :relationship,
options_for_select(
Relationship.all.map{|rel| [rel.name, rel.id]},
#order.relationship.id.to_s ),
prompt: 'Please select', class: "form-control"
I get an Called id on nil error as this is trying to set a selected value which doesn't exist yet.
I'm on rails 3.13
my Order model has a belongs_to relationship with the Relationship model
Thanks for your help.
I have multiple identical collection selects inside a single form. I prefer this over a multiple select list for aesthetic and UX reasons. I have to use a terrible kludge to make everything work right, and I'm wondering if there is a more elegant way to do this:
From the view:
<% 3.times do |i| %>
<%= collection_select("selected_item_" + i.to_s.to_s, :name, #items, :name, :name, { :include_blank => true }, { id: "selected_item_" + i.to_s }) %>
<% end %>
From the controller:
ItemContainer = Struct.new(:name)
3.times do |i|
param = ('selected_item_' + i.to_s).to_sym
instance_variable = '#' + param_name
if params[param] && !params[param].empty?
#selected_items << params[param][:name]
instance_variable_set(instance_variable, ItemContainer.new(params[param][:name]))
end
end
#selected_channels.each.... # do what I need to with these selections
Most of these gymnastics are needed to ensure that the item is still selected if the page is refreshed. If there were some way to force collection select to use arrays, that would be the answer, but I couldn't make that work.
If I understang right you're looking for selegt_tag method (docs: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag)
You can write something like this
select_tag "people[]", options_from_collection_for_select(#people, "id", "name")
select_tag "people[]", options_from_collection_for_select(#people, "id", "name")
and it youd output two selects for people, which would be sent as an array on submit.
if you use the [] naming in your collection_select calls then the params will send over the data as an array
I am a bit confused as to the usage of collection_select here as it doesn't seem like you are using a model object? this example using select_tag - might be able to come up with something more appropriate to your issue if the model structures were known
# run this in the loop
# set selected_value to appropriate value if needed to pre-populate the form
<%= select_tag('name[]',
options_from_collection_for_select(#items, 'name', 'name', selected_value),
{ include_blank: true }
)
%>
in controller update/create action
# this works because the select tag 'name' is named with [] suffix
# but you have to ensure it is set to empty array if none are passed, usually only issue with checkboxes
names = params[:name] || []
names.each do |name|
puts name
end
side note: you can use string interpolation with ruby double quotes in places of + for string concatenation
<%= collection_select("selected_item_#{i}",
:name,
#items,
:name,
:name,
{ include_blank: true },
{ id: "selected_item_#{i}" }
)
%>
see also: http://apidock.com/rails/v3.2.13/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
With the code I have below in the select field I have all the public_campaigns:
<%= f.select :campaign_id, #public_campaigns.map{|x| [x.name,x.id]} %>
public_campaigns is defined in controller with:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
In the form I select the campaign and fill up the rest of the form and at the submit action an invitation is created with campaign_id taken from the campaign I selected in the form, it can be anything from 1 to n
What I need now is to have a default item in select field that will have the value of 0 and named "No campaign", it means I invite someone to a campaign that I have not created yet and in invitation the campaign_id field will be 0.
Thank you for your time.
Do you really need 0? I think use of {:include_blank => "No campaign"} should be enough?
Try this:
<%= f.select :campaign_id, (#public_campaigns.map{|x| [x.name,x.id]} << ["No campaign",0]), {:selected => 0} %>
Well, the fastest way you can do this is something like this:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
no_campaign = Campaign.new(:id => '0', :name => 'No Campaign')
#public_campaigns.unshift(no_campaign)
I'm not sure why you are unable to do it this way:
<%= f.collection_select :campaign_id, #public_campaigns, :id, :name, prompt: 'No campaign' %>
Just check if campaign_id.nil? instead of assigning any value to campaign_id