Elijah Murray
Elijah Murray

Reputation: 2172

Is build_ Syntactic Sugar?

I'm learning rails, and can't find a good way to search for this, as Google doesn't like underscores. What's build_* do as a prefix? Does it make an initializer for whatever model you attach it to?

Upvotes: 4

Views: 961

Answers (2)

Adnir Andrade
Adnir Andrade

Reputation: 11

I came here to resurrect this in case anyone is looking for the same answer - Brainmaniac is right and the link he provided is updated. You can, in fact, do the other way around as well. But instead of "build_", you will have to use something like:

In case of "has_one": @parent.build_children(parameters)

In case of "has_many": @parent.children.build(parameters)

Upvotes: 1

JaTo
JaTo

Reputation: 2832

It is related to associations. You can use it on a child class's object to build the parent association. You can't use it the other way around.

class Puppy
  belong_to :dog
  attr_accessor :name
end

class Dog
  has_many :puppies
  attr_accessor :name
end

p = Puppy.new(name: "baby")
p.build_dog(name: "John)

Upvotes: 6

Related Questions