我在Rails 3應用程序上使用formtastic和haml。我正在嘗試爲調查和問題製作一個嵌套表單,但它不適合我。我觀看了railscast以及其上的所有內容,但似乎無法使其適用於我的應用程序。所以現在,我有以下幾點:爲什麼accept_nested_attributes_for不適合我? (rails 3)
模式
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"
表單呈現正確,但是當我更改問題並單擊保存時,記錄不反映我的更改。我有調試(params)打開,這裏是它回來爲:
--- !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"
我在做什麼錯在這裏?我不想手動編寫這些屬性更改器!
這結束了,但我忘了重新回答:P – 2011-01-20 15:57:22
任何想法爲什麼[Nested Object Forms](http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes)介紹doesn不需要attr_accessible? – Turadg 2011-02-08 00:19:09
爲我工作。謝謝。 – 2012-04-15 06:49:45