简体   繁体   中英

ArgumentError wrong number of arguments (1 for 3..4)

I get an ArgumentError for line #3 in my views/-/new.html.erb file that states:

"wrong number of arguments (1 for 3..4)"

<div class='form-group'>
    <%= form.label :category %>
    <%= form.select "category", options_from_collection_for_select([{1 => 'Food'}, {2 => 'Entertainment'}]) %>
</div>

The Application trace states:

app/views/events/new.html.erb:14:in block in _app_views_events_new_html_erb__1569841425540097418_70204987081640' app/views/events/new.html.erb:5:in _app_views_events_new_html_erb__1569841425540097418_70204987081640'

erb:14 is line #3 above, and erb:5 is

<%= form_for @event do |form| %>

The error message is being thrown by options_from_collection_for_select([{1 => 'Food'}, {2 => 'Entertainment'}])

[{1 => 'Food'}, {2 => 'Entertainment'}] is an array being passed as one argument to options_from_collection_for_select method; hence the error message.

The correct form for calling the options_from_collection_for_select helper method is

options_from_collection_for_select(collection, value_method, text_method, selected = nil)

See more details and usage examples at http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

I think you'd be better off using options_for_select , which will work with the arguments you've provided and just replace the options_from_collection_for_select in your code. The documentation for which can be found here .

You need to decide whether you want the number (1, 2 etc.) or the word (Food, Entertainment etc.) to be the "value" which reaches your back-end. For example:

options_for_select({'Food' => 1, 'Entertainment' => 2})

The output of the above in HTML would be as follows:

<option value="1">Food</option>
<option value="2">Entertainment</option>

The options_from_collection_for_select method requires 3 arguments. You've only provided one: [{1 => 'Food'}, {2 => 'Entertainment'}] . Your second argument should be a method/attribute on each object in the collection which represents the "value", the third should be the label for that value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM