简体   繁体   中英

Rails 4, build / create multiple table entries in the controller from passed in params

I am new to rails and am trying to create multiple entries in a table through my Test and TestQuestions models without success. Ultimately I would like to select 50 questions based on their category. I am stuck at this step, trying to pass category_id parameters to update my test_questions table from the TestController / Test Model.

The commented out line in the controller below: "@test.test_questions.build(:question_id => 5).save" works to make one question number 5, but when I call @test.build_category_test!(category_params).save instead to call a method and pass an array,I get the error undefined method `build_category_test!' for #Test:0x000000047f0928

Models

class TestQuestions < ActiveRecord::Base
  belongs_to :test 
end

class Test < ActiveRecord::Base
  has_many :test_questions, class_name: "TestQuestions",
                            foreign_key: "test_id"

  def self.build_category_test!(category_ids)
    unless category_ids.blank?
      category_ids.each do |u|
        test_questions.build!(:question_id => 5)        
      end
    end
  end
end

Controller

class TestsController < ApplicationController
  def create
  @test = Test.new(test_params)

  respond_to do |format|
    if @test.save
      #@test.test_questions.build(:question_id => 5).save
      @test.build_category_test!(category_params).save
      format.html { redirect_to @test, notice: 'Test was successfully created.' }
      format.json { render action: 'show', status: :created, location: @test }
    else
      format.html { render action: 'new' }
      format.json { render json: @test.errors, status: :unprocessable_entity }
    end
  end

  def category_params
    params[:category][:category_ids]
  end

end

View of test/new.html.erb

<%= form_tag tests_path, :method => :post do %>
<%= hidden_field_tag "user_id", @user_id %>
<ul>
<% for c in @categories %>
  <li>
  <%= check_box_tag "category[category_ids][]", c.id %>
  <%= c.category %>
  </li>
<% end %>
</ul>
<%= submit_tag "Create Test" %>

Log of parameters: "user_id"=>"1", "category"=>{"category_ids"=>["1", "2"]}, "commit"=>"Create Test"}

The method build_category_test! should be an instance method:

def build_category_test!(category_ids) # @test.build_category_test!

Instead of a class method:

def self.build_category_test!(category_ids) # Test.build_category_test!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM