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.

Projects can be created only by admins<br />

7.1 Projects can be created only by admins<br />

To restrict the creation of projects to admins, you alter the existing Background in<br />

features/creating_projects.feature and insert the following listing as the first three lines.<br />

Listing 7.1 features/creating_projects.feature<br />

Given there are the following users:<br />

| email | password |<br />

| admin@ticketee.com | password |<br />

And I am signed in as them<br />

This listing creates a user. The Background should now look like the following listing.<br />

Listing 7.2 features/creating_projects.feature<br />

Given there are the following users:<br />

| email | password | admin |<br />

| admin@ticketee.com | password | true |<br />

And I am signed in as them<br />

Given I am on the homepage<br />

When I follow "New Project"<br />

There’s a problem here: the admin attribute for User objects isn’t mass-assignable. You<br />

saw this issue in chapter 6 when the attr_accessible method was introduced. This<br />

restriction means that you can’t assign the admin attribute along with other attributes<br />

using the new, build, create, or update_attributes method.<br />

You have to set this attribute manually by using either update_attribute or the<br />

setter, user.admin = [value]. You use the latter here, so change this step in features/<br />

step_definitions/user_steps.rb<br />

Given /^there are the following users:$/ do |table|<br />

table.hashes.each do |attributes|<br />

unconfirmed = attributes.delete("unconfirmed") == "true"<br />

@user = User.create!(attributes)<br />

@user.confirm! unless unconfirmed<br />

end<br />

end<br />

to this:<br />

Given /^there are the following users:$/ do |table|<br />

table.hashes.each do |attributes|<br />

unconfirmed = attributes.delete("unconfirmed") == "true"<br />

@user = User.create!(attributes)<br />

@user.update_attribute("admin", attributes["admin"] == "true")<br />

@user.confirm! unless unconfirmed<br />

end<br />

end<br />

If you pass the admin attribute in your table, it’ll be a string. You check whether the<br />

string is equal to true, and if it is, you use update_attribute to set the admin field manually<br />

to true or false, depending on whether or not attributes["admin"]is true.<br />

137

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

Saved successfully!

Ooh no, something went wrong!