I am working through agile web development with rails 4th edition (rails 3.2+) and had a question about migraitons. There is an exercise where I have to add a column to an existing table and then update that new column with values. I need to add a ‘price’ column to ‘line_items’ table. First I generated the migration:
rails generate migration add_price_to_line_items price:decimal
Then I edited the migration file:
class AddPriceToLineItems < ActiveRecord::Migration
def change
add_column :line_items, :price, :decimal
LineItem.all.each do |li|
li.price = li.product.price
end
end
def down
remove_column :line_items, :price
end
end
Everything worked as planned, however, I had a question about attr_accessible. It is my understanding that all attributes of an object need to be specified in attr_accessible in order to be edited. If not, you usually get this error:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: product
As such, all attributes must be set as parameters of attr_accessible in the associated model:
class LineItem < ActiveRecord::Base
**attr_accessible :cart_id, :product_id, :quantity**
belongs_to :cart
belongs_to :product
def total_price
product.price * quantity
end
end
If this is true, then how was my migration able to update the newly generated column? If the column had just been generated, then that new attribute would not yet be specified in the attr_accessible of the associated model. Any and all input would be appreciated.
Basicaly it is because in rails forms you can add any field to a form. if a user add a new parameter to the form and submit it to your server it can gives you very big problems.
Like this:
your controller:
if this is your controller the user insert (by javascript or by console editing on chrome) a new textfield he can modify protected fields.
thats why we use
attr_accessibleto allow only the defioned fields.so the atributes that are not in
attr_accessibleare still acessible, just not acessible to make a mass assign.you still can do things like this:
model has name, time and date:
controller or any class:
You can:
You can’t:
if you still dont understand check this link http://ruby.railstutorial.org/chapters/modeling-users#sec:accessible_attributes it has a great explanation