rails fields_for在嵌套表单上的验证错误后不呈现

时间:2010-08-31 17:23:39

标签: ruby-on-rails

我有一个嵌套的表单问题。我实现了railscasts 196& amp;的嵌套表单解决方案。如果我没有验证错误,它就可以工作。

因此,表单在加载时会完美呈现,包括嵌套字段(在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

观点的一部分:

<% 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' %>&nbsp;
  </div> <!-- /formBtn -->
<%- end -%>

3 个答案:

答案 0 :(得分:12)

是否会抛出错误?

我的猜测是您的问题是,在您的new操作中,您正在执行@property.images.build,这不在您的编辑操作中。验证失败时,它将呈现您的新操作,但不会运行您的新操作。您可以尝试将@property.images.build放在create操作的else子句中,例如:

else
  @property.images.build
  render :action => 'new'
end

无论如何,这不是最干净的方式,但这有助于追踪这是否是您的问题。

答案 1 :(得分:3)

我也遇到了与此行为相同的问题。由于我看不到您的模型,我猜您有:reject_if =&gt; :all_blank或其他一些lambda。这似乎是罪魁祸首,虽然我没有修复。我会把它留作评论而不是答案,但显然我没有足够的声誉去做这样的事情。

答案 2 :(得分:1)

此时此刻,我发现修复它的唯一方法就是覆盖了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
希望它有所帮助!