Reputation: 5396
Hi I'm new in ruby and rails and I want to create a new attribute email for the model Account. Down below is the test for my new attribute. The test is a copy of the name attribute test but i figured that they will be working in a similar way.
it "should have a email field" do
@account.email = "email"
@account = save_and_reload(@account)
@account.email.should == "email"
end
The only thing I've done to make the test pass is to create a email attribute in the account model. And I have also manually inserted a new column email in the database account table.
Here is part of the account model code where I've inserted the email attribute:
class Account < ActiveRecord::Base
attr_accessible :name, :logo, :account_preference_attributes,:email
When i run the test I get the error NoMethodError in 'Account should have a email field'
undefined method `email=' for #<Account:0xb6468ca8>
So how do I create a new attribute in the model?
Upvotes: 1
Views: 1539
Reputation: 47548
I think you're confusing attr_accessible
with attr_accessor
. The former is how Rails protects attributes from mass-assignment, while the latter is a Ruby directive which creates reader and writer methods for instance variables.
If you just want to use an instance variable in your model, use attr_accessor
. If you want to create a persistent attribute, where the value gets stored to a column in the table, create a migration and add the column there.
Upvotes: 2
Reputation: 2792
I think the problem occurs because you've only changed it on your development database, tests run on a seperate database that gets reset everytime you run your testsuite.
Make a migration and then run the following command to migrate your test environment, or leave out the RAILS_ENV part to just do it for development:
rake db:migrate RAILS_ENV=test
Upvotes: 1
Reputation: 7288
You have to create a migration to add email column into the table and run rake db:migrate
class AddSsl < ActiveRecord::Migration def self.up add_column :accounts, :email, :string end def self.down remove_column :accounts,:email end end
Also remove the email column from the table that you have manually added.
Upvotes: 2