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.

548 APPENDIX B Tidbits<br />

You should get back the number 1 from this. If you didn’t have the id prefix in your<br />

routes and instead had something like make-it-shiny, you would need to save this<br />

string to a field in the table called something obvious like permalink by using a<br />

before_create method; then rather than using find in places where you are searching<br />

for an object, you would instead use find_by_permalink.<br />

B.2 Attribute change tracking<br />

When working with Active Record, you have the ability to check if a field has changed<br />

since the last time you made reference to this record. Let’s try this now with a Project<br />

object in the ticketee project by first launching rails console.<br />

Within this console, let’s create a new Project object:<br />

>> project = Project.new<br />

On any ActiveRecord::Base descendant, you can call the changed? method to determine<br />

if it has changed since it was created or found. Let’s call it:<br />

>> project.changed?<br />

=> false<br />

In this case, the project hasn’t changed from when it was created and so the changed?<br />

method returns false. If you set any attribute on this object, the changed? method<br />

will return true:<br />

>> project.name = "Ticketee"<br />

=> "Ticketee"<br />

>> project.changed?<br />

=> true<br />

Now if you want to know what fields have caused this change, you can just drop off the<br />

question mark at the end of changed?, like this:<br />

>> project.changed<br />

=> ["name"]<br />

As you can see here, this method returns an array containing the attributes which<br />

have changed on this object. If you changed another attribute on this project, such as<br />

created_at, it would also appear in this list:<br />

>> project.created_at = Time.now<br />

=> [current time]<br />

>> project.changed<br />

=> ["name", "created_at"]<br />

If you wanted to know only if a single attribute has changed, there’s the *_changed?<br />

methods for all attributes on the model. For instance, if you wanted to know if the<br />

name attribute has changed, then you would call name_changed?:<br />

>> project.name_changed?<br />

=> true

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

Saved successfully!

Ooh no, something went wrong!