ネストされたモデルフォーム(改訂) Railscastを使用して、一度に更新できるネストされたモデルを含むページを作成しようとします。Wikiには多くのトピックがあり、多くのメモがあります。
問題は、a)既存のデータが、これが正しく実行されている場合のようにフィールドに事前入力されていないこと、およびb)更新を押してもエラーがスローされないことです(実際、成功バナーが表示されます)。 )、しかしそれも何もしません。
これが私のコードです:
wiki、topic、note.rb(実際には読んでいないために組み合わせて):
class Wiki < ActiveRecord::Base
attr_accessible :topics_attributes
has_many :topics
accepts_nested_attributes_for :topics, :allow_destroy => true
end
class Topic < ActiveRecord::Base
attr_accessible :name, :notes_attributes, :wiki_id
has_many :notes
belongs_to :wiki
accepts_nested_attributes_for :notes, :allow_destroy => true
end
class Note < ActiveRecord::Base
attr_accessible :name, :info, :topic_id
belongs_to :topic
end
wikis_controller.rb
wikiが1つだけ必要なので、wiki.firstを実行しています。モデルが存在するため、単一のオブジェクトを介して依存モデルを更新できます。私はその1つ以上のウィキを持つことは決してありません。
class WikisController < ApplicationController
before_filter :authorize
def show
@wiki = Wiki.first
end
def edit
@wiki = Wiki.first
end
def update
@wiki = Wiki.first
respond_to do |format|
if @wiki.update_attributes(params[:wiki])
format.html { redirect_to wikis_path, notice: 'Wiki was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @wiki.errors, status: :unprocessable_entity }
end
end
end
end
ルート.rb #「wiki」を1つだけ必要とし、そのルートを/ wikis get'wikis'、to:'wikis#show'、as:'home' resources:wikis
wikis / edit.html.haml
.row.container.wiki
%h1{ :style => 'margin-bottom: 40px'} Update the Wiki
= form_for @wiki do |w|
= w.fields_for :topics do |builder|
= render "topic_fields", f: builder
= link_to_add_fields "add topic", w, :topics
%br
= w.submit "Update", class: "btn"
wikis / _topic_fields.html.haml
.field_inset
= f.text_field :name
= f.hidden_field :_destroy
= link_to "remove", '#', class: "remove_fields"
= f.fields_for :notes do |builder|
= render 'note_fields', f: builder
wikis / _notes_fields.html.haml
.field_inset
.add_inset
= f.fields_for :notes do |builder|
.remove
= builder.text_field :name
= builder.text_field :info, class: "no_margin"
= link_to "remove", '#', class: "remove_fields"
一部のjavascriptを呼び出すremove_fieldsを除いて、クラスは主にスタイリング用です。私がここで間違っていることについて何か考えはありますか?私はこれにかなり困惑しています。
新しいエラー
wikis_controller(誤ってparams [:post]を参照していた)で更新アクションを修正した後、更新を送信しようとするとこのエラーが発生するようになりました。それでも、フィールドは事前入力されていません。
Can't mass-assign protected attributes: notes
:topics_attributesと:notes_attributesがこれを処理すると思いましたか?
また、Notesフィールドは事前入力されていませんが、Topicsフィールドは事前入力されていることに注意してください。
編集-以下の一括割り当てエラーからのパラメータハッシュ
パラメータが正しく渡されているようです
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"3/4k8eEa4/PfeNI9cSj7zqCm9+scWBS3gwEacmc/hd0=",
"wiki"=>{"topics_attributes"=>{"0"=>{"name"=>"Pre-existing Topic Name",
"_destroy"=>"false",
"notes_attributes"=>{"0"=>{"notes"=>{"name"=>"New Notes Name",
"info"=>"New Notes Info"},
"id"=>"1"}},
"id"=>"1"}}},
"commit"=>"Update",
"id"=>"1"}