Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 ActiveRecord API: .build method

I am fairly new to Ruby/RoR (outside of a year) and I have noticed that there are several different methods inside of RoR or Ruby that basically do the same thing. The one method I am wanting to get some sort of clarification on, is the .build method. when it is effective to use or how to use it in its best light, sorta thing.

Thanks!

like image 378
dennismonsewicz Avatar asked Aug 22 '11 19:08

dennismonsewicz


1 Answers

The .build method is an ActiveRecord method which is used to create a new record based on the has_many relationship in your model.

So lets say;

User has_many tweets

Then you can use

user.tweets.build(tweet_id)

This will create a new tweet in the tweets table associated with that user. It will also return that object too.

You probably want to put a params tweet_id in you argument depending on how you are implementing the app. :)

like image 130
Vishal Sakaria Avatar answered Nov 03 '22 22:11

Vishal Sakaria