ruby - Rails - Best-Practice: How to create dependent has_one relations -


Can you tell me what is the best practice to build a relationship?

F.E. If I have a user model, and have a profile in it ...

How can I complete this?

There will be a solution:

  # user.rb class user & lt; & Lt; ActiveRecord :: base after_create: set_default_association def set_default_association self.create_profile end and  

but it does not look very clean ... does any suggestions?

has_one is the best practice to make a relationship using ActiveRecord callback before_create Instead of using after_create or using any first callback and dealing with the children who do not pass their own verification phase (if any)

Because:

  • With good coding, you have the opportunity to record the child's records for the user, if assumptions fail,
  • It is actively and clearly supported by the Active Record - the AR automatically fills the foreign key in the child's record, (on making) the AR saves hair records as part of creating original records.
  • How to do this:

      # user model ... is_one: create before profile: build_default_profile private def build_default_profile # Build Default Profile Example Will use the default parameter # The foreign key for the ownering user model is automatically set to build_profile true # Always correct as a normal 'release' status in the callback # Believe that default_profile ** can always be ** created # Or check the verification of # profiles if it is not valid, #back false from callback. Best to use beforehand first # If this is the code should check the child's errors. Add # or child errors to the error category of the user model: Base # error item end  

Comments