Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, I assume that <code>User</code> model persists in your Rails app. That means, that you already have a <strong>migrated <code>User</code></strong> model before running <code>rails console</code>.<br> If that table doesn't exist, you will be instanly prompted with:</p> <blockquote> <p>=> User(Table doesn't exist)</p> </blockquote> <p>Now, let's have some fun in <code>rails console</code>:<br> First things first, don't override <code>initialize</code> method in Rails model; While creating an object initialize method from ActiveRecord takes precedence (I think), so it may create conflicts. Instead use <code>after_initialize</code> callback. In console: </p> <pre><code>class User &lt; ActiveRecord::Base attr_accessible :name, :email def after_initialize(attributes = {}) self[:name] = attributes[:name] self[:email] = attributes[:email] end def formatted_email "#{self.name} &lt;#{self.email}&gt;" end end </code></pre> <p>Now, </p> <pre><code>u = User.new({name: "Foo", email: "foo@bar.org"}) #&lt;User name: "Foo", email: "foo@bar.org", created_at:nil updated_at: nil&gt; u.formatted_email #=&gt; "Foo &lt;foo@bar.org&gt;" </code></pre> <p>All done! Sweet. </p> <p><strong>UPDATE</strong>:<br> As per your recent <a href="https://gist.github.com/gprasant/e9d454bc0246dbba1e18" rel="nofollow">gist</a>; I see no point of having <code>after_initialize</code> at all. Rails does that on it's own.<br> First thing first, replace <code>attr_accessor</code> with <code>attr_accessbile</code>.<br> <code>attr_accessor</code> is ruby method(courtesy, metaprogramming) which creates getter and setter for provided instance variable. Rails uses <code>attr_accessible</code> for that; for security concerns, only instance variables allowed in <code>attr_accessible</code> allowed for mass-assignment (by sending params hash). </p> <p><code>user.rb</code></p> <pre><code>class User &lt; ActiveRecord::Base attr_accessible :name, :email #def after_initialize(attributes = {}) # self[:name] = attributes[:name] # self[:email] = attributes[:email] #end def formatted_email "#{self.name} &lt;#{self.email}&gt;" end end </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