使用一个表单创建多个记录

时间:2013-01-21 10:36:20

标签: ruby-on-rails forms nested-attributes

我正在尝试使用嵌套表单,但不断收到以下错误:

ActiveModel :: MassAssignmentSecurity :: ResponsesController中的错误#create

无法批量分配受保护的属性:gate_answer

以下是我的模特......我做错了什么?

class Response < ActiveRecord::Base
  attr_accessible :gate_id, :gate_answers_attributes
  belongs_to :gate
  has_many :gate_answers
  accepts_nested_attributes_for :gate_answers
end

class GateAnswer < ActiveRecord::Base
  attr_accessible :prospect_id, :gate_question_id, :content, :response_id
  belongs_to :response
end

数据库架构提取:

create_table "gate_answers", :force => true do |t|
  t.integer  "prospect_id"
  t.integer  "gate_question_id"
  t.text     "content"
  t.datetime "created_at",                      :null => false
  t.datetime "updated_at",                      :null => false
  t.integer  "response_id"
end

create_table "responses", :force => true do |t|
  t.integer  "gate_id"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

..和我的控制器

# responses_controller.rb

def create
  @response = Response.new(params[:response])

  respond_to do |format|
    if @response.save
      format.html { redirect_to :action => 'index', :gate_id => (params[:response][:gate_id]), notice: 'Response was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end


#gate_answers_controller.rb

def create

@gate_answer = GateAnswer.new(params[:gate_answer])

#code below finds URL that user will be redirected to after form is saved
@gate = Gate.find(params[:gate_answer][:gate_id])

  respond_to do |format|
    if @gate_answer.save
      format.html { redirect_to @gate.content_url, notice: 'Redirecting.' }  #redirect to URL per above
    else
      format.html { render action: "new" }
    end
  end
end

我做错了什么?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

创建此类表单的方法在Railscasts Nested Model Form Part 1&amp; Part 2。也许这会对你有帮助吗?