27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Restricting read access<br />

This message occurs because you haven’t defined a belongs_to association between<br />

the Permission objects and the users they relate to. To set up this association, open<br />

app/models/permission.rb and define it using a simple belongs_to:<br />

belongs_to :user<br />

That’s the first association you need to define, and when you run this feature again,<br />

you get a second error that looks similar to the first:<br />

And "user@ticketee.com" can view the "TextMate 2" project<br />

unknown attribute: thing (ActiveRecord::UnknownAttributeError)<br />

This code represents a polymorphic association, which as mentioned earlier, needs to<br />

associate with many types of objects. A polymorphic association uses the thing_type<br />

and thing_id fields to determine what object a Permission object relates to.<br />

To define this association in your model, use this line:<br />

belongs_to :thing, :polymorphic => true<br />

Figure 8.1 illustrates how this association works.<br />

When you assign an object to the thing polymorphic association, instead of just<br />

saving thing_id as in a normal belongs_to, Rails also saves the thing_type field,<br />

which is the string version of the object’s class, or thing.class.to_s. In this step of<br />

your application, the thing_type field is set to Project because you’re assigning a<br />

Project object to thing. Therefore, the new record in the table has both thing_type<br />

and thing_id attributes set.<br />

When Rails loads this object, it goes through the process shown in figure 8.2. Rails<br />

knows this is a polymorphic association because you told it in the Permission model,<br />

and it therefore uses the thing_id and thing_type fields to find the object. By knowing<br />

thing_type, Rails can figure out what model the association is and then use that<br />

Permission<br />

thing = Project(id = 1)<br />

thing.id thing.class.to_s<br />

Permission(thing_id<br />

= thing.id)<br />

Permission(thing_type =<br />

thing.class.to_s)<br />

Permission(thing_id = 1, thing_type = Project)<br />

Figure 8.1 Polymorphic saving<br />

167

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

Saved successfully!

Ooh no, something went wrong!