簡體   English   中英

Rails 4,通過傳入參數在控制器中構建/創建多個表條目

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM