Build in ruby on rails

Asp.net Tools
build_association(attributes = {})

The 'build' method in associations returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object’s foreign key will be set, but the associated object will not yet be saved.The 'build' method for associations is described as same as the

'new' method, but with the automatic assignment of the foreign key.The 'build' and 'new' functions have the same effect of setting the foreign key, when they are called through an association.

Example

@customer = @reservation.build_customer(:customer_ id=> 1)


Build method is from "ActiveRecord" base classs

collection.build(attributes = {})

Returns a new object of the collection type that has been instantiated with attributes and linked to this object through the join table, but has not yet been saved.

By using build method we can save two records at a time
For example i have two models user and articles and having one to many relation between them which means one user can have many articles

Then i can able to save a new user record and the article record belongs to that user at time using build method.

Example :

irb(main):001:0> user=User.new(:name=>"myname",:email=>"sree@gmail.com")

=> #<User id: nil, name: "myname", email: "sree@gmail.com", created_at: nil, updated_at: nil>

irb(main):003:0> user.articles.build(:title=>"climate",:description=>"season of the climate at present is rainy")

=> #<Article id: nil, title: "climate", description: "season of the climate at present is rainy", user_id: nil, created_at: nil, updated_at: nil, price: nil>

irb(main):005:0> user.save
=> true

irb(main):007:0> user.articles
=> [#<Article id: 47, title: "climate", description: "season of the climate at present is rainy", user_id: 14, created_at: "2011-07-22 02:40:45", updated_at: "2011-07-22 02:40:45", price: nil>]

user created using new method and articles belong to that user is created using build method and save that user, at a time two records are saved.

Thanks
Sriram

Facebook Rss Twitter

Get Weekly News letter of Updates!