I am working on a simple intranet application made with Rails 3.1.
I have a model for links which has the following fields:
name:string
url:string
colour:string
I have put the colour attribute into a class in the view, like so:
<a href="linkaddress" class="<%= link.colour %>">Link Name</a>
At the moment in the new link form I just have a simple form input in which the user can type anything and it will become the href class as expected.
What I would like to do is create a dropdown list of preset options, these options are simply red, green and blue (as an example). As this seems fairly simple, I don't think there is any need for a helper.
I have read a few other questions and answers on SO and they seem to show examples where you have the name followed by an ID number. I just want to have the code below:
<select name="colour">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
I'm sure this is simple but I can't get my head around it. I've read the Rails API info and the select_for_tag has confused me!
Just use a standard select element in your form to set the colour variable:
<%= f.select :colour, options_for_select([["Red", "red"], ["Green", "green"]], @link.colour) %>
Where Colour is the name of your model for your colours and f is the form builder object:
<%= f.collection_select :colour, Colour.all, :url, :name %>
This would be the simplest and most straightforward approach to get a select with the colour's url as the value and the name as the text. If you want both the name for the value and text, you can change :url to :name as well.
In addition, and for semantics, you'd also probably want to set a @colours collection in your controller and use it rather than calling to the model from your view (to replace Colour.all).
UPDATE: Based on your comment below and if you don't have a model for the collection and simply want to hardcode your select and values, try:
<%= select :your_obj, :linkaddress, [["Red","red"],["Green", "green"],["Blue", "blue"]] %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With