Search code examples
ruby-on-railsrubyrails-activerecordsti

Creating form for STI Model


Referring to this post: Rails: Deal with several similar model classes?

Using combination of STI and Store feature to organize very similar models.

"Declare a base model for Student with a text column called settings.

class Student < ActiveRecord::Base
  store :settings
  # name, email, phone, address etc..
end

class HighSchoolStudent < Student
  # declare HighSchoolStudent specific attributes 
  store_accessor :settings, :gpa
end

How can I create a form for a HighSchoolStudent, while remaining under the Student controller?

I dont want to add a separate controller or route resource for HighSchoolStudent, is there a way to have one form for Student and HighSchoolStudent, with a checkbox to indicate whether its a Student or a HighSchoolStudent? Can I only require that the extra attributes created for the subclass are only required for the form to be submitted if that specific class is checked?

<%= simple_form_for(@student, html: {class: "form-horizontal"}) do |f| %>
<%= f.input :name, as: :text, input_html: {rows: "1"} %>
<%= f.input :email, as: :text, input_html: {rows: "2"} %>

<%= f.input :gpa, as: :text, input_html: {rows: "1"} %>


<%= f.button :submit, class: "btn btn-primary" %>

Solution

  • Sure, you can make an arbitrary checkbox, and check its value in the create action:

    # In your view
    <%= check_box_tag :high_school %>
    
    # In your controller
    def create
      base_class = params[:high_school] ? HighSchoolStudent : Student
      base_class.create(params[:student])
      ...
    end
    

    Any validations specific to HighSchoolStudent will be ensured only if the checkbox was checked.