Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual attributes and mass-assignment

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!

like image 403
Fivell Avatar asked Jan 25 '12 15:01

Fivell


People also ask

What is mass assignment in Rails?

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.

What is mass assignment in Java?

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 are virtual attributes rails?

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).

What is virtual attribute in Ruby?

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.


1 Answers

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
like image 174
Dylan Markow Avatar answered Sep 22 '22 22:09

Dylan Markow