2014-03-26 18 views
0

我是rails的新手,並試圖通過我的Test和TestQuestions模型在表中創建多個條目而未成功。最終,我想根據他們的類別選擇50個問題。我被困在這一步,試圖傳遞category_id參數來更新TestController/Test Model中的test_questions表。Rails 4,在傳遞參數的控制器中構建/創建多個表項

下面控制器中註釋掉的一行:「@ 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 

測試的查看/ 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」=>「創建測試」}

回答

1

的方法build_category_test!應該是一個實例方法:

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

而是一個類的方法:

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

進入方法,你可能想是這樣的:!'test_questions.create(:question_id => u)'。在控制器中,移除'.save' – markets

+0

謝謝!我也改變了「建立!」在該方法中「構建」,並從控制器中移除「.save」並且它工作。我也會嘗試「創造!」並進行其他更改以使其更加實用。 – user3291025

+1

根據市場的建議,最終的工作方法使用「創建!」 – user3291025

相關問題