Ruby on Rails form select

2019-02-26 21:54发布

问题:

Hey guys I'm a rails newbie and I have a question about select boxes in forms. Here is my code right now.

<%= form_for @message do |f| %>
  <%= f.text_field :name %>
  <%= f.select :topic ['Test1', 'test2']
<% end %>

Now, this code works for submitting the information in the text boxes, but for some reason not the information in the select box. However my main question is, Is there a way that I can make a select box and rails automatically include: "Please select an option" and that way when I do validates_presence_of :topic on the select box it will return false if it hasn't been changed?

Also, do any of you think you know why the select box isn't submitting info to my database?

Thanks in advance!

回答1:

Yes, what you want is easy to do. Just add a pair of values, your placeholder text and a blank value, to the beginning of your select options. Try this:

<%= f.select :topic, [['Please select an option', nil], 'Test1', 'test2'] %>