When do I need to use build when creating new records

14 views
Skip to first unread message

fugee ohu

unread,
Mar 31, 2019, 5:39:40 PM3/31/19
to Ruby on Rails: Talk
I can create a new record from the model on the right side of a has_many statement Why user the model on the left plus . plus the model on the right plus build The reason I'm asking is because I came across this piece of code below As you can see it's a little primitive placing the seller's name in the auction model instead of leaving it alone and rendering in views from the records in User I'm gonna remove seller_name from the table

   @auction = current_user.auctions.build(params[:auction])
    @auction.seller_name = current_user.name

Douglas Lovell

unread,
Apr 1, 2019, 6:32:42 AM4/1/19
to Ruby on Rails: Talk
The `build` method constructs the ORM object without validating or saving. It provides an opportunity to configure attributes before saving, before validating. If you feel good about the `params[:auction]`, have them filtered with `require` and `permit`, and aren't going to groom the record any further, then `create` or `create!` will serve. When using `create` it's necessary to check the return value for failures. With `create!` you'll have the `ActiveRecord::RecordInvalid` or other exception to capture on failure.
Reply all
Reply to author
Forward
0 new messages