Create interdependent association model in rails - Best pratice -
what best practice creating associated models e.g. not want save if 1 of validation fails(say c). also, show error each model if any.
class has_many :b has_many :c end class b end class c end class acontroller def create afields = params[:a_params] bfields = params[:b_params] cfields = params[:c_params] = a.new(a_params) if a.save b.create(bfields) c.create(cfields) redirect_to a_index else redirect_to a_new_path end end end basically, want create lot of interdependent models , want save of them or none if single validation fails. can way or other know best way it.
you can use activerecord validation's validates_associated method serve purpose:
class < activerecord::base has_many :b has_many :c validates_associated :b, :c end edit:
you alternatively use, validates_associated in b , c models this:
class b < activerecord::base belongs_to :a validates_associated :a end class c < activerecord::base belongs_to :a validates_associated :a end that way, ensure associated a present before creating b's record or c's record.
but careful, can't use validates_associated in both associations (has_many , belongs_to) cause infinite recursion.
Comments
Post a Comment