我有一个嵌套的表单问题.我实现了railscasts 196和197的嵌套表单解决方案.如果我没有验证错误,它可以工作.
因此,表单在加载时会完美呈现,包括嵌套字段(在fields_for部分中).
但是,表格有验证.验证失败时,控制器会渲染: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
Run Code Online (Sandbox Code Playgroud)
部分观点:
<% form_for :property, @property, :url => { :action => "create" }, :html => { :multipart => true } do |f| %>
<div id="new-property-form-spannedcols">
<div class="formField inptRequired">
<%= f.label :postal_code, t("Postal_code") %>
<%= f.text_field :postal_code, :class => 'inptMedium short' %>
</div>
<div id="city_row" class="formField inptRequired">
<%= f.label :city, t("City") %>
<div id="city_cell">
<%= render :partial => 'ajax/cities', :locals => { :postal_code => @property.postal_code } %>
</div>
</div>
...
<% f.fields_for :images do |builder| %>
<div class="formField">
<%= builder.label :photo, t("Photo_path_max_3mb") %>
<%= builder.file_field :photo, :class => 'inptMedium' %>
<%= builder.hidden_field :order, :value => "1" %>
</div>
<% end %>
</div> <!-- /new-property-form-spannedcols -->
<div class="formBtn">
<%= f.submit t("Save"), :class => 'btnMedium bg-img-home' %>
</div> <!-- /formBtn -->
<%- end -%>
Run Code Online (Sandbox Code Playgroud)
the*_*eIV 12
它会抛出错误吗?
我的猜测是你的问题是在你的new行动中,你正在做@property.images.build,这不在你的编辑行动中.验证失败时,它将呈现您的新操作,但不会运行您的新操作.您可以尝试将动作@property.images.build的else子句放入create:
else
@property.images.build
render :action => 'new'
end
Run Code Online (Sandbox Code Playgroud)
无论如何,这不是最干净的方式,但这将有助于追踪这是否是您的问题.