Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an ActiveRecord with values in Rails?

In plain java I'd use:

public User(String name, String email) {   this.name = name;   this.email = f(email);   this.admin = false; } 

However, I couldn't find a simple standard way to do in rails (3.2.3), with ActiveRecords.

1. override initialize

def initialize(attributes = {}, options = {})   @name  = attributes[:name]   @email = f(attributes[:email])   @admin = false end 

but it might be missed when creating a record from the DB

2. using the after_initialize callback

by overriding it:

def after_initialize(attributes = {}, options = {})   ... end 

or with the macro:

after_initialize : my_own_little_init def my_own_little_init(attributes = {}, options = {})   ... end 

but there may be some deprecation issues.

There are some other links in SO, but they may be out-of-date.


So, what's the correct/standard method to use?

like image 260
Asaf Avatar asked May 08 '12 19:05

Asaf


People also ask

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is initialize method in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What are Initializers in rails?

An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.


2 Answers

Your default values should be defined in your Schema when they will apply to ALL records. So

def change   creates_table :posts do |t|     t.boolean :published, default: false     t.string :title     t.text :content     t.references :author     t.timestamps   end end 

Here, every new Post will have false for published. If you want default values at the object level, it's best to use Factory style implementations:

User.build_admin(params)  def self.build_admin(params)   user = User.new(params)   user.admin = true   user end 
like image 152
Jesse Wolgamott Avatar answered Sep 19 '22 10:09

Jesse Wolgamott


According to Rails Guides the best way to do this is with the after_initialize. Because with the initialize we have to declare the super, so it is best to use the callback.

like image 33
Mauro George Avatar answered Sep 22 '22 10:09

Mauro George