developers! I can't understand next situation
For Example I have model
class Pg::City < ActiveRecord::Base
belongs_to :country
#virtual accessors
attr_accessor :population
#attr_accessible :city, :isdisabled, :country_id
end
I can use code like this:
c = Pg::City.new({:population=>1000})
puts c.population
1000
But if I uncomment attr_accessible code above throw warning
WARNING: Can't mass-assign protected attributes: population
How can I use virtual attributes for mass-assigmnment together with model attributes? Thanks!
Mass Assignment is the name Rails gives to the act of constructing your object with a parameters hash. It is "mass assignment" in that you are assigning multiple values to attributes via a single assignment operator.
Mass assignment is a computer vulnerability where an active record pattern in a web application is abused to modify data items that the user should not normally be allowed to access such as password, granted permissions, or administrator status.
What is 'Virtual Attribute'? The Virtual Attribute is a class attribute, which has no representation in the database. It becomes available after object initialization and remains alive while the object itself is available (like the instance methods).
Ruby actually lets you create virtual attributes this way, which keeps you from having to manually create getter and setter methods as given below, attr_reader :title # getter. attr_writer :title # setter. attr_accessor :title # both getter and setter.
Using attr_accessor
to add a variable does not automatically add it to attr_accessible
. If you are going to use attr_accessible
, then you will need to add :population
to the list:
attr_accessor :population
attr_accessible :city, :isdisabled, :country_id, :population
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With