How to create a Rails form using inheritance and nested attributes?

I have a polling application, mainly on Railscast 196 , but with one catch: where Railscast has one Questionclass, which has_many :answers, I have several:

Question (self.abstract_class = true)
BasicQuestion < Question
MultipleChoiceQuestion < Question

To do this, I had to redefine gett questionsin Survey, which seems a bit ragged but not too bad (is there a standard way to do this?):

Survey.rb
has_many :questions
accepts_nested_attributes_for :questions

def questions # simplified a bit for brevity
  questions = []
  [BasicQuestion, LikertQuestion, MultipleChoiceQuestion].each do |model|
    questions += model.where(:survey_id => self.id)
  end
  questions
end

Survey_Controller.rb
def survey_params
    params.require(:survey).permit(:name, :questions_attributes => [:id, :name])
end

So far so good. The problem is this:

Again from Railscast, I have this in surveys/edit.html.erb:

surveys/edit.html.erb
<%= f.fields_for :questions do |builder| %>
    <%= render 'edit_question_fields', f: builder %>
<% end %>

However, this returns a form hash:

{ "survey" => { "name" => "Howard", questions_attributes => { "id" => "1", "name" => "Vince" }}}

Rails gives me an error: ActiveRecord::StatementInvalid (Could not find table '')- presumably because there is no table questions(this is an abstract class).

, ? nested_attributes , :

  • STI ( Question, ), _type hash .
  • Survey :

    Survey.rb
    has_many :basic_questions
    accepts_nested_attributes_for :basic_questions
    has_many :multiple_choice_questions
    accepts_nested_attributes_for :multiple_choice_questions
    
    def questions
      # same as before, still comes in handy
    end
    
    surveys/edit.html.erb
    <% @survey.questions.each do |question| %>
      <%= f.fields_for question do |builder| %>
        <%= render 'edit_question_fields', f: builder %>
      <% end %>
    <% end %>`
    

    , , :

    { "survey" => { "name" => "Howard", "basic_question" => { "id" => "1", "name" => "Vince" }, "multiple_choice_question" => { "id" => "1", "name" => "Naboo" }}}
    

    , , , "basic_questions_attributes" "basic_question" - - , ?

  • questions_attributes= Survey.rb, .

  • QuestionsFormBuilder, "Rails / .

, Question ( ) .

№ 3, , , . ( - Question.) - Rails ?!

+4

All Articles