Ruby attr_accessible, validates, attr_accessor, cattr_accessor

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

attr_accessible

The new Model which has a attr_accessible, from English full name is attibutes accessible, literally means property access
For example, rails g model User name:string email:string, will create the following files and automatically add attr_accessible


class User <ActiveRecord::Base
attr_accessible :name, :emailend
end


If not attr_accessible, then the default is not accessible, it is a security mechanism.


validates

Verification of validates_presence_of ,validates_length_of, validates_numericality_of ,allow_nil, allow_blank, message, on
After Rails3
validates :email, :presence =>true,
:length => {:minimum => 3, :maximum => 254, :message => "Incorrect length" },
:uniqueness => true,
:email => true
validate :my_validation errors[:base] <<"can not be xxx"


Attr_reader and attr_accessor

Is mainly used to set or read the value attribute in the class;.Attr_reader is read only, cannot be set, and the attr_accessor can be read also can set the cattr_accessor

cattr_accessor

The static class variables is equivalent to Java, sharing on all instances.





Protection of rails data form: attr_accessor, attr_accessible and attr_protected

(http://www.cnblogs.com/rywx/archive/2012/05/20/2510597.html)

Attr_accessor is built in Ruby language, this method is the automatic generation of get set method variables, which can save a lot of repetitive get set method.
Attr_accessible and attr_protected is provided by the rails framework





ActiveModel:: MassAssignmentSecurity:: Error error?

Rails 3.2.8 version of 3.2.X config/application.rb config.active_record.whitelist_attributes default will be set to true, Let a lot of Fu value (Mass assignment) function failure (chapter for safety), Result L = Location.new (example: event => E) ActiveModel:: MassAssignmentSecurity:: Error: Can't mass-assign protected attributes: event error. Solution 1 to modify the config/application.rb config.active_record.whitelist_attributes is set to false 2 or is separated from the Fuvalue l=Location.new; l.event = e

Rails 4 and later don't have this problem, the config.active_record.whitelist_attributes set is removed, the default back to allow large Fu value (Mass assignment), so the book examples do not correct.
params.require(:person).permit(:name, :age)

http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Felix at December 20, 2013 - 5:53 PM