我懷疑這可能是一個非常簡單的錯誤,但我花了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的大規模任務嗎? – 2012-01-14 23:58:56
是的,這就是爲什麼有[MassAssignmentSecurity](http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible)來幫助你分享你的屬性。但是你通過形式來設置article_ids通過質量分配。 – Vapire 2012-01-15 10:21:06
這可能是一個切線有點離開,但爲了我自己的理解,不要在控制器中使用'@ article.subsections.build'自動設置外鍵'article_id'?儘管如此,我繼續嘗試,但這並沒有解決問題。 – 2012-01-15 22:58:08