Rails:allow_destroy =>在Active Record中嵌套属性嵌套属性适用于开发但不适用于生产

时间:2016-03-10 04:39:18

标签: ruby-on-rails postgresql activerecord heroku nested-attributes

我在rails应用程序中使用嵌套表单并按如下方式设置:

型号:

class Location < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :location, dependent: :destroy
  accepts_nested_attributes_for :location, allow_destroy: true 
end  

控制器:

class PostsController < ApplicationController

  def edit     
    if @post.location.blank?
     @post.build_location
    end
  end

  def update    
    if @post.update_attributes(post_params)
      flash[:success] = "Post was upated."
      redirect_to edit_category_post_path(@category, @post)
    else
      flash[:danger] = "There was an error saving a post, please try again."
      render :new
    end
  end

  def post_params
    params.require(:post).permit(:title, :body, location_attributes: [:id, :street, :city, :zipcode, :state, :_destroy])
  end

end

查看:

应用程序/视图/位置/ _form.html.erb

<div class="form-group">
  <%= f.check_box :_destroy %> 
  <%= f.label :_destroy, "Delete." %> 
  </br>

  <%= f.label :street %> (optional)
  <%= f.text_field :street, class: 'form-control',placeholder: "123 A Street" %>
</div>

应用程序/视图/帖/ _form.html.erb

<div class="well">
  <%= f.fields_for :location do |location| %>
    <%= render 'locations/form', f: location %>
  <% end %>
</div>

在开发模式下,一切都按预期工作。在开发中,当我测试编辑功能时,我在位置表单中单击了destroy复选框,删除了location对象并且location_id变为nil。但是,在推送到Heroku之后,我发现NestedAttributes中的:allow_destroy => true选项无法正常工作并创建以下错误:

PG::ForeignKeyViolation: ERROR:  update or delete on table "locations" violates foreign key constraint "fk_rails_ccec1da3aa" on table "posts"
DETAIL:  Key (id)=(2) is still referenced from table "posts".

在控制台中,location_id仍然连接到post对象。我试图在控制台中删除该对象,但它仍然显示相同的错误。由于某些原因,一旦使用post创建了location对象,我就无法在生产模式中使用destroy复选框删除location对象。

过去两天我一直在研究所有可能的解决方案,但到目前为止,我还没有找到解决方案。

注意: 就我而言,我希望在删除post对象时保留location

1 个答案:

答案 0 :(得分:0)

删除location失败,因为您可能 antoher post引用locationClass Post ... belongs_to: location)。

您需要删除引用location的所有帖子,然后才能删除location