简体   繁体   中英

How do I properly use a select box with ruby on rails?

I have a select box for the event types of an event. event belongs to event_type and event_type has many events. Here's what I have for the select box:

<%= f.select :event_type, options_from_collection_for_select(EventType.all, :id, :name, @event.id), :placeholder => 'Select an event type' %>

But, the problem is that when I submit it, it submits the id of the event type and not the name of it. So, how would I make it submit the name rather than the id? If you need to see the any more code than just tell me, thanks

The second parameter to options_from_collection_for_select is the value that will be submitted with the form. You have :id , so change it to :name .

http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

(but this seems like a strange thing to do - typically you would store the event type ID.)

You should pass name in the Value method, if you want to pass the name,

<%= f.select :event_type, options_from_collection_for_select(EventType.all, :name, :name, @event.id), :placeholder => 'Select an event type' %>

Here is the doc for options_from_collection_for_select

You can use the id after the submit to load the event type again in your controller post action like this:

selected_type = EventType.find(params[:event_type]

It is also a good practice to keep database calls to the controller, so please put the EventType.all statement in there and pass it as local or class variable like you did with event .

If you really want to pass the name in your form instead of the id, you can replace the :id part in your call to something more like this options_from_collection_for_select(@event_types, :name, :name, @event.event_type.name) . Keep in mind that this value should be unique!

The method works like this:

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

So the first parameter contains all the options, the second defines the value within those option objects which are put into the value field of the HTML option (which is being submitted by the form), the third defines the text which is displayed to the user and the final parameter defines the value of the selected entry (in case you are editing an entry for example). For the last parameter, you need to use the events' event_type id, or in your case, the name because you set the value of your HTML tag to it.

Use pages like ApiDock or the Rails tutorials to get examples for some of these methods. http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

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