Search code examples
ruby-on-railsassociationsmodels

Editing associated models the rails way


I have a model "Student" and every student has_many parents (a mother and a father in the parents table). In my UI I want to be able to add the parents and the student on the same page. So when I click on "Add student" the view 'students/new' is rendered. In this view I have the regular stuff for adding a student (<% form_for @student....) so far so good. But now I also want to provide the form for adding a mother and a father for this student on the same page. I know I could place a link to 'parents/new' somewhere but that is not really user-friendly in my opinion.

What are my options and what would you recommend?


Solution

  • Your best bet would be using nested_forms with accepts_nested_attributes_for like below

    #student.rb
    Class Student < ActiveRecord::Base
    has_many :parents
    accepts_nested_attributes_for :parents
    end
    
    #students_controller.rb
    
    def new
    @student = Student.new
    @student.parents.build
    end
    
    def create
    @student = Student.new(student_params)
    if @student.save
    redirect_to @student
    else
    render 'new'
    end
    
    private
    
    def student_params
    params.require(:student).permit(:id, :student_attr_1, :student_attrr_2, parents_attributes: [:id, :father, :mother])
    end
    
    #students/new
    
    <%= form_for @student do |f| %>
    ---student code here ---
    <%= f.fields_for :parents do |p| %>
    <%= p.label :father, :class => "control-label" %>
    <%= p.text_field :father %>
    <%= p.label :fmother, :class => "control-label" %>
    <%= p.text_field :mother %>
    <% end %>