Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object in ActiveRecord without initialize method?

Consider a model without an initialize method, defined as follows:

class User < ActiveRecord::Base  
end

It has 2 properties: name & age.

It is possible to create a new object by calling User.new('Joe Brown', 21)? Is there another "shorthand" way of creating the object?

Or do you have to define an initialize method in order to do this in one line?

like image 381
B Seven Avatar asked Jan 28 '26 18:01

B Seven


2 Answers

With ActiveRecord:

User.new(:name => "Joe Brown", :age => 21)
like image 189
Kyle Avatar answered Jan 30 '26 11:01

Kyle


You can also specify the fields :

User.new :name => "Joe Brown", :age => 21

or

User.new name: "Joe Brown", age: 21
like image 43
Thomas Guillory Avatar answered Jan 30 '26 12:01

Thomas Guillory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!