Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>attr_accessor</strong> and <strong>attr_accessible</strong>, despite almost identical spelling, are absolutely different methods.</p> <p><strong>attr_accessor</strong>, a native Ruby method which defines a getter and a setter method for the instance of the class:</p> <pre><code>class User attr_accessor :password end u = User.new u.password = "secret" u.password # =&gt; "secret" </code></pre> <p><strong>attr_accessible</strong> is a method brought by Rails and it is meant to "whitelist" <em>already existing</em> attributes of a model. Attributes enumerated in <strong>attr_accessible</strong> can be later changed via mass-assignment of model attributes (while other attributes will be blacklisted and not changeable):</p> <pre><code>class Account &lt; ActiveRecord::Base # First, you define 2 attributes: "password" and "created_at" attr_accessor :password attr_accessor :created_at # Now you say that you want "password" attribute # to be changeable via mass-assignment, while making # "created_at" to be non-changeable via mass-assignment attr_accessible :password end a = Account.new # Perform mass-assignment (which is usually done when you update # your model using the attributes submitted via a web form) a.update_attributes(:password =&gt; "secret", :created_at =&gt; Time.now) a.password # =&gt; "secret" # "password" is changed a.created_at # =&gt; nil # "created_at" remains not changed </code></pre> <p>You use <strong>attr_accessible</strong> to prevent meddling with some attributes of your models by "outsiders" (e.g. you wouldn't want your "Account.superadmin" attribute to be changeable via a simple form submission, which would be a bad security issue).</p> <p>Note, that you can change the attributes individually, regardless of their "whitelisting/blacklisting" status:</p> <pre><code>a.created_at = Time.now a.created_at # =&gt; 2012-09-16 10:03:14 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload