これは非常に単純な間違いかもしれないが、私はそれを探して3時間を費やしたので、コミュニティの助けを求めるかもしれないと思った。Rails 3.1:ネストされた属性はフォームに保存されません
私は、Ryan Batesのネストされたモデルフォームの優れたスクリーンキャストを実行しており、自分のプロジェクトにそれらを適用しようとしています。問題は、ネストした属性がフォームを使用して保存していないように見えることです。私はコンソールを介して保存することができますが、それはフォームを通過するときに空の括弧で表示されます。
ここに関連するコードは次のとおり
(HAMLを使用して)フォームビュー
= form_for(@article) do |f|
- if @article.errors.any?
#error_explanation
%h2
= pluralize(@article.errors.count, "error")
prohibited this article from being saved:
%ul
- @article.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :title
%br/
= f.text_field :title
.field
= f.label :intro
%br/
= f.text_area :intro
= f.fields_for :subsections do |builder|
= render 'subsections_fields', :f => builder
.field
= f.label :published_at
%br/
= f.text_field :published_at
.actions
= submit_or_cancel(f)
subsection_fieldsビューを形成
= f.label :header
%br/
= f.text_field :header
= f.label :order_id
= f.number_field :order_id
%br/
= f.label :body
%br/
= f.text_area :body
%br/
= f.check_box :_destroy
= f.label :_destroy, "Remove Subsection"
%br/
コントローラ
class ArticlesController < ApplicationController
def new
@article = Article.new
3.times { @article.subsections.build }
end
def create
@article = Article.new(params[:article])
if @article.save
flash[:notice] = "Successfully created article."
redirect_to @article
else
render :action => 'new'
end
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
flash[:notice] = "Successfully updated article."
redirect_to @survey
else
render :action => 'edit'
end
end
def destroy
Article.find(params[:id]).destroy
flash[:notice] = "Succesfully destroy article."
redirect_to articles_url
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
end
とモデル
class Article < ActiveRecord::Base
attr_accessible :title, :intro
has_many :subsections, :dependent => :destroy
accepts_nested_attributes_for :subsections, :reject_if => lambda { |a| a[:body].blank? },
:allow_destroy => true
has_and_belongs_to_many :categories
validates :title, :presence => true
end
class Subsection < ActiveRecord::Base
attr_accessible :header, :body, :order_id
belongs_to :article
validates :header, :presence => true
validates :body, :presence => true
end
これを考え出すすべてのヘルプははるかに高く評価されます。
私はかなり新しいレールですが、これは危険ではありませんか?これは、誰かが記事IDの一括割り当てを行うことを許可していないのですか? –
はい、それはあなたの属性をサニタイズするのを助けるために[MassAssignmentSecurity](http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible)がある理由です。しかし、フォームを介してmass assignmentによってarticle_idsを設定しています。 – Vapire
これはたぶん接線を外しているかもしれませんが、私自身の理解のために、コントローラの '@ article.subsections.build'を使用しないと自動的に外部キー' article_id'が設定されますか?私は先に進み、とにかくそれを試みたが、これは問題を解決しない。 –