[英]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. 我是Rails的新手,正在尝试通过Test和TestQuestions模型在一个表中创建多个条目,但没有成功。 Ultimately I would like to select 50 questions based on their category. 最终,我想根据其类别选择50个问题。 I am stuck at this step, trying to pass category_id parameters to update my test_questions table from the TestController / Test Model. 我被困在这一步,试图传递category_id参数以从TestController / Test Model更新我的test_questions表。
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!' 下面控制器中的注释行:“ @ test.test_questions.build(:question_id => 5).save”使一个问题编号为5,但是当我致电@ test.build_category_test!(category_params).save时,调用一个方法并传递一个数组,我得到错误的未定义方法“ build_category_test!”。 for #Test:0x000000047f0928 适用于#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 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"} 参数的日志:“ user_id” =>“ 1”,“ category” => {“ category_ids” => [“ 1”,“ 2”]},“ commit” =>“ Create Test”}
The method build_category_test!
方法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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.