rails fields_for在嵌套表单上的validation错误后不呈现
我有一个嵌套的表单问题。 我实现了railscasts 196和197的嵌套表单解决方案。如果我没有validation错误,它就可以工作。
因此,表单在加载时会完美呈现,包括嵌套字段(在fields_for部分中)。
但是,表格有validation。 validation失败时,控制器会渲染:new。 然后表单呈现链接的模型字段,但不再渲染嵌套字段。 这有解决方案吗?
控制器
def new @property = Property.new @property.images.build end def create @property = Property.new(params[:property]) if @property.save flash[:success] = t('Your_property') + ' ' + t('is_successfully_created') redirect_to myimmonatie_url else render :action => 'new' end end
部分观点:
{ :action => "create" }, :html => { :multipart => true } do |f| %> 'inptMedium short' %> 'ajax/cities', :locals => { :postal_code => @property.postal_code } %> ... 'inptMedium' %> "1" %> 'btnMedium bg-img-home' %>
它会引发错误吗?
我的猜测是你的问题是,在你的new
动作中,你正在做@property.images.build
,这不在你的编辑动作中。 validation失败时,它将呈现您的新操作,但不会运行您的新操作。 您可以尝试在create
操作的else子句中放置@property.images.build
,如:
else @property.images.build render :action => 'new' end
无论如何,这不是最干净的方式,但这将有助于追踪这是否是您的问题。
我也遇到了同样的问题。 由于我看不到你的模型,我的猜测是你有:reject_if =>:all_blank或其他一些lambda。 这似乎是罪魁祸首,虽然我没有修复。 我会把它留作评论而不是答案,但显然我没有足够的声誉去做这样的事情。
在这一刻,我发现修复它的唯一方法是只覆盖create方法。
def new @property = Property.new @property.images.build end def create @property = Property.new(params[:property]) if @property.save flash[:success] = t('Your_property') + ' ' + t('is_successfully_created') redirect_to myimmonatie_url else @property.images.build if @property.images.blank? ##because i'm shure you have something similar to : accepts_nested_attributes_for :images, :reject_if => lambda { |fields| fields[:image].blank? } render :action => 'new' end end
希望能帮助到你!