0

我在这方面被困了几天,虽然我设法找到了一些相关的答案,但似乎没有什么能完全涵盖我需要的两个功能。

基本上我有一个“问题”和“答案”模型。我想显示与问题一样多的答案字段,并使用我的自定义控制器创建它们。如果未登录,我还想分配会话 ID,或者将用户 ID 分配给答案(这样我就可以在他们注册后确定谁回答了)。我设法显示了这些字段,但现在它们不会保存,我得到的只是视图上的“内部错误”消息和控制台上的异常:

!! Unexpected error while processing request: expected Array (got Rack::Utils::KeySpaceConstrainedParams) for param `question'

这是我的模型/控制器的样子:

step1_controller.rb

class Configurator::Step1Controller < ApplicationController
    before_filter :authenticate_user!

  def new
    @questions = Question.includes(:choices).all()
  end

  def create
    Question.update_attributes(params[:question].keys, params[:question].values)
    flash[:notice] = 'Reports were successfully updated.'
    redirect_to root_path
  end

end

模型/answer.rb

class Answer < ActiveRecord::Base
  attr_accessible :weight, :user_id, :question_id
  belongs_to :user
  belongs_to :question
end

模型/问题.rb

class Question < ActiveRecord::Base
  attr_accessible :created_at, :desc, :updated_at, :title, :created_by_id, :updated_by_id, :tag_id, :answers_attributes
  belongs_to :created_by, :class_name => 'User'
  belongs_to :updated_by, :class_name => 'User'
  belongs_to :tag
  has_many :choices
  has_many :answers
  has_many :user, :through => :answers
  accepts_nested_attributes_for :answers
end

路线.rb

namespace :configurator do get "step1", :to => 'step1#new', :as => :step1 post "step1" => "step1#create", :as => :step1 end

看法

<%= form_for :question, :url => configurator_step1_path do -%>
      <% for question in @questions %>
       <%= fields_for "question[]", question do |question_fields| %>
        <%= question_fields.hidden_field :id %>
        <%= question_fields.label :title, question.title %>
        <%= question_fields.fields_for :answers, [Answer.new] do |li_fields| %>
          <%= li_fields.text_field :weight %>
          <% end %>
        <% end %>
        <% end %>
      <%= submit_tag "Create line items" %>
        <% end %>
       <% if false %>
      <%= f.fields_for :answers, [Answer.new]*5 do |li_fields| %>
      <%= li_fields.label :weight %>
      <%= li_fields.text_field :weight %>
         <% end %>
      <br>
   <% end %>
4

1 回答 1

0

您可能想看看这个 railscast http://railscasts.com/episodes/196-nested-model-form-revised

同样在您的控制器中,而不是:

Question.update_attributes(params[:question].keys, params[:question].values)

你可以这样做:

Question.update_attributes(params[:question])
于 2013-06-24T15:47:55.377 回答