0

I'm attempting to automatically build a child model when its parent is created, as noted in this post. Say I have two models Person has_one :folder and I would like to create a folder when the person creates To do this I go into the Person model and (from the example above) do the following.

has_one :folder
before_create :build_default_folder

private
def build_default_folder
  build_folder
  true
end

This makes sense, but say Profile had some attributes that I would like to set an attribute for Folder based on the Person's attributes. Like if the person has :person_name what should I do to set :folder_name as "[person_name]'s_Folder"?

Thanks for any suggestions.

Community
  • 1
  • 1
neanderslob
  • 2,633
  • 6
  • 40
  • 82

1 Answers1

1

You able to access a parent attribute from the child model:

class Profile < AR::Base
    has_one :folder
    before_create :build_default_folder

    private
    def build_default_folder
      build_folder(folder_name: person_name)
      true
    end
end

Read the documentation for Active Record Associations.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103