As a reminder to myself, here are some notes on how to add a boolean column to a table in rails3.
Step 1: Create migration
rails generate migration add_public_to_listings admin:boolean
Step 2: Write unit tests on model
listing_spec.rb
describe "admin attribute" do before(:each) do @listing = @user.listings.create!(@attr) end it "should respond to public" do assert_respond_to(@listing, :public) end it "should not be public be default" do assert !@listing.public end it "should be converible" do @listing.toggle!(:public) assert @listing.public end end
Step 3: Update test data
populate.rake
def make_listings puts "----------------" puts "--- listings ---" puts "----------------" myUser = User.find_by_email("a@a.com") ls1 = myUser.listings.create!(:title => "The Mona Lisa", :description => "Master peice", :category_id => 2, :address => "T3H0E2", :location => "Calgary, Alberta, Canada") ls1.toggle!(:public)
Note: We set the :public value through the toogle for security reasons. Only those variables exposed via attr_accessible
class Listing < ActiveRecord::Base
attr_accessible :title, :description, :category_id, :address, :location
can be set through mass assignment. This prevents bad guys from changing values like this:
put /listings/17?public=1
Thanks again Michael for the great example.
Filed under: rails Tagged: rails31, RoR, ruby, rubyonrails
