dannymcc
dannymcc

Reputation: 3814

Rails 3 dropdown select boxes?

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!

Upvotes: 7

Views: 18344

Answers (3)

miked
miked

Reputation: 4499

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"]] %>

Upvotes: 4

Jon
Jon

Reputation: 10898

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) %>

Upvotes: 13

Mgrandjean
Mgrandjean

Reputation: 317

You want to use the rails helper, because then rails will take care of moving the data into your model. so you most likely want something like the following.

<%= f.select :colour, ["red","green","blue"] %>

This Page can be a bit wordy, but it might help how you're thinking about it.

Upvotes: 3

Related Questions