27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Changing a ticket’s state<br />

There you have it! The State model is up and running. Let’s now<br />

associate this class with the Comment class by adding this line to the<br />

top of the Comment model’s definition:<br />

belongs_to :state<br />

The state method provided by this belongs_to will be used shortly to display the<br />

state on the ticket page, as in figure 10.6.<br />

Before doing that, however, you need to add the select box for the state to the<br />

comment form.<br />

10.2.2 Selecting states<br />

In the comment form partial, add this select box underneath the text box, as shown in<br />

the following listing.<br />

<br />

<br />

@ticket.state_id %><br />

<br />

Listing 10.11 app/views/comments/_form.html.erb<br />

Here you use a new method, select, which takes its first argument as the foreign-key<br />

attribute of your Comment object, not the association. You also use the :state_id value<br />

for the argument passed to the label, but Rails is smart enough to know the text for<br />

this should be “State”. select’s second argument is a two-dimensional 3 Array that you<br />

create by using map on the State objects returned from the controller in the @states<br />

variable. The first element of each array is the value you want shown as an option in<br />

the select box to the user, whereas the second element is the value that’s passed back<br />

to the controller.<br />

Use the :selected option in the select call to select the current state of the ticket<br />

from the list. This value must match the value argument for one of the options in the<br />

select box; otherwise it will default to the first option.<br />

Let’s assume for a moment that you’ve got three states: New, Open, and Closed.<br />

For a ticket that has its state set to New, the select box generated by f.select would<br />

look like this:<br />

<br />

New<br />

Open<br />

Closed<br />

<br />

3 A two-dimensional array is an array that contains arrays as elements.<br />

Figure 10.6<br />

A ticket’s state<br />

255

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!