Почему у меня не работает accept_nested_attributes_for? (рельсы 3)

Я использую formtastic и haml в приложении Rails 3. Я пытаюсь сделать вложенную форму для опросов и вопросов, но у меня это просто не работает. Я смотрел railscast, и про него, и все такое, но я не могу заставить его работать для моего приложения. Итак, прямо сейчас у меня есть следующее:

модели

class Survey < ActiveRecord::Base
  attr_accessible :intro, :name, :pubdate, :enddate, :pubid

  belongs_to :user
  has_many :questions, :dependent => :destroy, :autosave => true

  accepts_nested_attributes_for :questions, :allow_destroy => true
end

class Question < ActiveRecord::Base

  belongs_to :survey
  has_many :answers, :dependent => :destroy

  attr_accessible :q_text, :order, :q_type

end

соответствующий метод контроллера

def update
  @survey = Survey.find(params[:id])
  @user = current_user
  if check_auth_and_redirect @user, @survey
    if @survey.update_attributes(params[:survey])
      flash[:success] = "Survey Updated"
      redirect_to edit_survey_path(@survey)
    else
      @title = "Editing Survey #{@survey.id}"
      render 'edit'
    end
  end
end

просмотры

= semantic_form_for @survey do |f|
  = render "shared/survey_inputs", :object => f
  = f.inputs :for => :questions, :name => "Survey Questions" do |fq|
    %hr
    = fq.input :q_text, :label => "Question text"
    = fq.input :q_type, 
               :label => "Question type", 
               :as => :select,
               :collection => %w(text scale radio select)
    = fq.input :order, :label => "Question order"

Форма отображается правильно, но когда я меняю вопрос и нажимаю «Сохранить», записи не отражают мои изменения. У меня включена отладка (параметры), и вот что возвращается как:

--- !map:ActiveSupport::HashWithIndifferentAccess 
      utf8: "\xE2\x9C\x93"
      _method: put
      authenticity_token: CJCc9LvdoPjxwGJkhUnZjR0Z/c5Wt5VBT3bBr/wB4+A=
      survey: !map:ActiveSupport::HashWithIndifferentAccess 
        name: This is my survey
        intro: I've got a lovely bunch of coconuts. There they are all standing in a row.
        pubid: smargdab
        pubdate(1i): ""
        pubdate(2i): ""
        pubdate(3i): ""
        enddate(1i): ""
        enddate(2i): ""
        enddate(3i): ""
        questions_attributes: !map:ActiveSupport::HashWithIndifferentAccess 
          "0": !map:ActiveSupport::HashWithIndifferentAccess 
            q_text: one one one one one one one one one one one
            q_type: text
            order: "3"
            id: "1"
          "1": !map:ActiveSupport::HashWithIndifferentAccess 
            q_text: 2 2 2 2 2 2 2 2 2 2
            q_type: text
            order: "1"
            id: "2"
          "2": !map:ActiveSupport::HashWithIndifferentAccess 
            q_text: 3 3 3 3 3 3 3 3 3 3
            q_type: text
            order: "2"
            id: "3"
      commit: Update Survey
      action: update
      controller: surveys
      id: "2"

Что я здесь делаю не так? Я не хочу писать эти сменщики атрибутов вручную!


person Brian Hicks    schedule 22.09.2010    source источник


Ответы (2)


Я смотрю на свой старый код, который использует accept_nested_attributes_for, и я думаю, что вам нужно изменить

attr_accessible :intro, :name, :pubdate, :enddate, :pubid

to

attr_accessible :intro, :name, :pubdate, :enddate, :pubid, :questions_attributes
person Chris Duesing    schedule 18.01.2011
comment
это закончилось тем, но я забыл ответить: P - person Brian Hicks; 20.01.2011
comment
Любые идеи, почему вложенный объект Вступление к формам не требует attr_accessible? - person Turadg; 08.02.2011

Я не разрешал определенные вещи в attr_accessible. Проблема в том, что я не знаю, что разрешить. Я думаю, что это questions_attributes, но, похоже, это не так.

person Brian Hicks    schedule 22.09.2010