Search code examples
ruby-on-railsrubysyntactic-sugar

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?


Solution

  • 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)