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