mercredi 27 avril 2016

How to update self referential association attributes in rails way?

I have one model which has has_many :through self referential association to it.

I'm creating and updating the child records in the single form, so far i'm successfully being able to create and update the child records using the manual approach. (Manually passing the Id of the parent record to the child)

I need to know/understand what should be the standard approach to create and update record for self referential association?

There are many reasons to follow the rails way here as it will help in handling errors at the creation part in a better way and also with updating child records and deleting one of the child records.

Model Template

class Template < ActiveRecord::Base

  has_many :related_templates, :foreign_key => :parent_id
  has_many :children, :through => :related_templates, :source => :child

  has_many :inverse_related_templates, class_name: "RelatedTemplate", :foreign_key => :child_id
  has_many :parents, :through => :inverse_related_templates, :source => :parent

end

Please note that my rails application is behaving as an api so i dont have rails forms in the views.

I need to know how will i white list the child attributes in the form and how will i write the create, update and delete method.

For white listing child attributes i tried using

accepts_nested_attributes_for :children and children_attributes in the controller but it is still unpermitted_parameter.

If needed i'll update my approach here (the manual way)

Aucun commentaire:

Enregistrer un commentaire