Multiple Record Save Action Pattern


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. def multiple_record_action
  2. if params[:id]
  3. @record = CustomRecord.find(params[:id])
  4. @dependent = @record.dependent
  5. else
  6. @record = CustomRecord.new
  7. @dependent = Dependent.new
  8. @dependent.record = @record
  9. end
  10. if request.post?
  11. @record.attributes = params[:record]
  12. @dependent.attributes = params[:dependent]
  13. begin
  14. @record.transaction(@record, @dependent) do
  15. @record.save
  16. @record.reload unless @record.id
  17. @dependent.save
  18. raise ActiveRecord::RecordInvalid unless @record.valid? && @dependent.valid?
  19. redirect_to :action=>'some_other_action'
  20. end
  21. rescue ActiveRecord::RecordInvalid
  22. end
  23. end
  24. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.