how can I get this to work?
<%= form_for current_user, html: {multipart: true } do |f| %>
<%= f.select(:brand, Brand.pluck(:company), {prompt:true}, {class: 'form-control'}, {:onchange => 'this.form.submit()'}) %>
<% end %>
The goal is to submit the form on change automatically. But the code above does not work. I get an wrong number of arguments (5 for 1..4) error. Any ideas?
The last three arguments there are actually a hash of options. Try putting them into curly braces to make it more clear, if you like:
<%= f.select(:brand, Brand.pluck(:company), {
prompt: true,
class: 'form-control',
onchange: 'this.form.submit()'
}) %>
Got it. Removed {prompt:true} and it works!
Select Helper:
select(object, method, choices = nil, options = {}, html_options = {}, &block)
This should work with prompt also:
<%= f.select(:brand, Brand.pluck(:company), {include_blank: true, class: 'form-control'}, :onchange => 'this.form.submit()') %>
Rails select helper
Related
I've got a fairly simple (it seems) bit of code to create a multiple-selection element:
<%= form_for #post do |f| %>
#stuff
<%= fields_for :tags |tag_fields| %>
<%= tag_fields.label :select_tags %>
<%= tag_fields.select :tags, Tag.all, multiple: true %>
<% end %>
<% end %>
For some reason when it renders the page, the multiple: true part isn't getting parsed, and the form is just rendering as a generic dropdown with only one option selectable. What am I missing?
(Rails version is 5.0.0 in case relevant)
The signature of the select helper is:
select(method, choices = nil, options = {}, html_options = {}, &block)
multiple is an HTML option, therefore you should use:
<%= tag_fields.select :tags, Tag.all, {}, multiple: true %>
The documentation for Rails select form helper states (see documentation):
select(object, method, choices = nil, options = {}, html_options = {}, &block)
Which allows adding a class simple, like so:
<%= f.select :some_attr, MYOPTIONS, {}, {class: 'my-class'} %>
My question is, how do I add a class to it when using it as a block? Rails documentation states:
select(report, "campaign_ids") do
available_campaigns.each do |c|
content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json })
end
end
It doesn't work when I use it like so:
<%= f.select :some_attr, {}, {class: 'my-class'} do %>
<% MYOPTIONS.each do |MYOPTION| do %>
<%= content_tag :option, MYOPTION.label, value: MYOPTION.value %>
<% end %>
<% end %>
Nor does it work if I use:
f.select :some_attr, class: 'my-class' do
The class is not applied to the select tag in the HTML.
I solved my own problem, although I don't fully understand the answer, so if someone else understands this better, I'd love to hear your answer.
To get it to work, I simply added an additional empty hash to the beginning, like so:
<%= f.select :some_attr, {}, {}, {class: 'my-class'} do %>
<% MYOPTIONS.each do |MYOPTION| do %>
<%= content_tag :option, MYOPTION.label, value: MYOPTION.value %>
<% end %>
<% end %>
The second hash is still options and the last is still html_options, so as an example, you can also add include_blank like so:
f.select :some_attr, {}, {include_blank: true}, {class: 'my-class'}
However, I don't know what the first hash is, nor what values can be passed there. I've looked at the Rails source, but I still have no clue. If you have insight into this, I'd love to hear it.
A couple oddities to be aware of:
In your example, you're using f.select, which you can find a reference for here:
https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Only the first parameters is required, the rest have defaults. However, to assign that HMTL class, you had to have a value for the fourth parameter, which necessitated having something for the second and third parameters as well.
What you ended up with is a valid solution:
<%= f.select :some_attr, {}, {}, {class: 'my-class'} do %>
<% MYOPTIONS.each do |MYOPTION| do %>
<%= content_tag :option, MYOPTION.label, value: MYOPTION.value %>
<% end %>
<% end %>
The block, when provided, takes precedence over the literal value (an empty hash in this case).
Surprisingly, if you were rendering this tag using select_tag instead of f.select, passing a block wouldn't be an option:
https://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag
I have a enum definition for my User model.
class User < ActiveRecord::Base
enum program_of_study: [
:program_of_study_unknown, :program_of_study_cs, :program_of_study_ceg,
:program_of_study_is, :program_of_study_science,
:program_of_study_engineering, :program_of_study_fass,
:program_of_study_business, :program_of_study_others
]
end
And in simple_form I have:
<%= simple_form_for(locals[:user], wrapper: :horizontal_form, html: {class: 'form-horizontal'},
url: {action: (locals[:is_new] ? 'create' : 'update')}) do |f| %>
<%= f.error_notification %>
<%= f.input :program_of_study, collection: User.program_of_studies, include_blank: false, selected: locals[:user].program_of_study %>
<%= f.button :submit, class: 'btn-success' %>
<% end %>
However, it seems that although the program_of_study of a user is 'program_of_study_science'(by checking in rails console), when I render the form, the shown select element still has 'program_of_study_unknown' as the displayed one. The correct one was not selected.
Instead of the enum I used the keys and it seems to work, have you tried that:
collection: User.program_of_studies.keys
I didn't have to specify a selected option. My code looks like this:
input :status, as: :select, collection: Venue.statuses.keys, include_blank: false
My solution in the end
<%= f.input :program_of_study, collection: User.program_of_studies, include_blank: false, selected: User.program_of_studies[locals[:user].program_of_study] %>
I know this question has been answered before, but none of the methods had worked for me.
I have a view with a select_tag that loads options from my database. <%= select_tag :nom, options_from_collection_for_select(Usuario.all, :id, :tienda), prompt: "Seleccionar tienda" %>
then, I use a link_to <%= link_to("Cargar", :action => 'rel') %><br>to load the query on my controller
def rel
#nom = params[:nom]
#tie = Av.find_by_sql(["SELECT * FROM avm.avs where usuario_id in(select id from avm.usuarios where tienda = ?)", #nom])
render('rel')
The problem is that when I select any value on my select_tag it does not pass that value and sets the value to nil...
I also used a collection_select and doesn't work either. <%= collection_select(:tienda, :tienda, Usuario.all, :id, :tienda)%>
I really broke my head off trying to figure out why. Thanks in advance!
Use form_tag:
<%= form_tag action: rel do %>
<%= select_tag :nom, options_from_collection_for_select(Usuario.all, :id, :tienda), prompt: "Seleccionar tienda" %>
<br>
<%= link_to("Cargar", '#', onclick: 'this.parentNode.submit(); return false') %>
<% end %>
Hint: replace find_by_sql by Arel:
#tie = Av.where("usuario_id IN (#{Usuario.select('id').where('tienda = ?', #nom).to_sql})")
I think you should put the select_tag in a form_tag block, and use submit_tag instead of link_to. If you just use a link no parameters will be passed to the controller (hence you get nil).
Something like:
<%= form_tag action: 'rel' do %>
<%= select_tag :nom, options_from_collection_for_select(Usuario.all, :id, :tienda), prompt: "Seleccionar tienda" %>
<%= submit_tag 'Cargar' %>
<% end %>
Just be mindful that this approach is not safe as there is no authenticity token verification.
My code:
<%= f.select :area, options_for_select([['a','a'],['b','b'],['c','c']]), {}, {:class => 'span3 controls controls-row'}, :selected => params[:area] %>
The result is:
ArgumentError in Users#edit
Showing /home/airson/rails_projects/friends_of_local/app/views/users/edit.html.erb where line #17 raised:
wrong number of arguments (5 for 4)
Why am I getting this error?
No need to use :selected just pass your params[:area] alone to options_for_select as a second argument:
<%= f.select :area,
options_for_select([['a','a'],['b','b'],['c','c']], params[:area]),
{}, { :class => 'span3 controls controls-row' } %>
The last value of your params[:area] will be selected.
Hope it helps ; )
You should pass :selected option to options_for_select method, like this:
<%= f.select :area, options_for_select([['a','a'],['b','b'],['c','c']], :selected => params[:area]), {}, { :class => 'span3 controls controls-row' } %>
The above answers didn't work for me on Rails 6.
This is what worked. Copied from one of the answers on Reddit
= f.select(:results, options_for_select(['Accepted', 'Not Accepted', 'Rejected', 'Acc', 'Rej', 'Information Only', 'N/A'], selected: #report.results || nil), { include_blank: "Select Result" }, { class: 'form-control select2', style: 'width: 100%;'})
Below is what worked for me using f.select with custom names and values including a blank field while using the Ransack search. Thanks to mayorsanmayor's example for getting me started in the right direction. This also works for rails 5.1.7.
<%= f.select(:status_eq, options_for_select([ ["Verified", "verified"], ["Non Verified","notVerified"]], selected: #q.status_eq || nil), {:include_blank => "Select Status"}, {class: 'form-control'}) %>