【问题标题】:Can't mass-assign protected attributes: _destroy无法批量分配受保护的属性:_destroy
【发布时间】:2012-12-01 20:31:46
【问题描述】:

我在提交嵌套表单时遇到了这个非常奇怪的错误。

Can't mass-assign protected attributes: _destroy

知道为什么会这样吗?这有点令人担忧,因为我不得不暂时用 javascript 删除 'destroy' hidden_​​field,直到我弄清楚它是什么,这意味着我不能删除任何东西!

_form.html.erb

<%= nested_form_for(@post, :html=> {:multipart => true, :class=> "new_blog_post", :id=> "new_blog_post"}) do |f| %>

 <%= field do %>
    <%= f.text_field :title, placeholder: "Give your post a title", :class=>"span12" %>
 <% end %>

 <%= field do %>
    <%= f.text_area :body, placeholder: "Write something here...", :id=>"blog-text", :class=>"span12" %>
 <% end %>

 <%= f.label :search_locations, "Add locations to your post" %>
    <%= text_field_tag :name,"",:class=>"localename", :id=>"appendedInput", :placeholder=> "Name of the location", :autocomplete => "off" %>
    <%= f.link_to_add "Add a location", :locations %>

 <%= actions do %>
   <%= f.submit "Submit", :class=>"btn", :disable_with => 'Uploading Image...' %>

<% end end%>

_posts_controller.rb_

class PostsController < ::Blogit::ApplicationController   

...   

def new
  @post = current_blogger.blog_posts.new(params[:post])
  @location = @post.locations.build

end



def edit
  @post = Post.find(params[:id])
  #@post = current_blogger.blog_posts.find(params[:id]) removed so any use can edit any post
  @location = @post.locations.build
end



def create
   location_set = params[:post].delete(:locations_attributes) unless params[:post][:locations_attributes].blank?

   @post = current_blogger.blog_posts.new(params[:post])

   @post.locations = Location.find_or_initialize_location_set(location_set) unless location_set.nil?


 if @post.save
    redirect_to @post, notice: 'Blog post was successfully created.'
  else
    render action: "new"
  end
end


def update
  @post = current_blogger.blog_posts.find(params[:id])
  if @post.update_attributes(params[:post])
    redirect_to @post, notice: 'Blog post was successfully updated.'
  else
    render action: "edit"
  end
end

def destroy
  @post = current_blogger.blog_posts.find(params[:id])
  @post.destroy
  redirect_to posts_url, notice: "Blog post was successfully destroyed."
end

location.rb

class Location < ActiveRecord::Base
  after_save { |location| location.destroy if location.name.blank? }

  has_many :location_post
  has_many :posts, :through => :location_post
  has_many :assets

   attr_accessible :latitude, :longitude, :name, :post_id, :notes, :asset, :assets_attributes
    accepts_nested_attributes_for :assets, :allow_destroy => true
    include Rails.application.routes.url_helpers


  def self.find_or_initialize_location_set(location_set)
   locations = []
   locations = locations.delete_if { |elem| elem.flatten.empty? }
   location_set.each do |key, location|

    locations << find_or_initialize_by_name(location)
  end
     locations
  end

 end

编辑:

new.html.erb 中呈现的表单片段

    <div class="row span locsearch">      
       <div class="input-append span3">

        <input autocomplete="off" class="localename" id="appendedInput" name="name" placeholder="Name of the location" type="text" value="">


        <span class="add-on"><input id="post_locations_attributes_0__destroy" name="post[locations_attributes][0][_destroy]" type="hidden" value="false"><a href="javascript:void(0)" class="remove_nested_fields" data-association="locations"><i class="icon-trash"></i></a></span>  </div>

<div class="latlong offset3 span4"> <p class="help-block">Enter the name of the town or city visited in this blog entry.</p>
        </div>

        <input class="LegNm" id="post_locations_attributes_0_name" name="post[locations_attributes][0][name]" type="hidden" value="Dresden">
        <input class="long" id="post_locations_attributes_0_longitude" name="post[locations_attributes][0][longitude]" type="hidden" value="13.7372621">
        <input class="lat" id="post_locations_attributes_0_latitude" name="post[locations_attributes][0][latitude]" type="hidden" value="51.0504088">

    </div>  
</div>

EDIT2:

post.rb

class Post < ActiveRecord::Base

require "acts-as-taggable-on"
require "kaminari"

acts_as_taggable    

self.table_name = "blog_posts"

self.paginates_per Blogit.configuration.posts_per_page

# ==============
# = Attributes =
# ==============
attr_accessible :title, :body, :tag_list, :blogger_id, :coverphoto, :locations_attributes



# ===============
# = Photo Model =
# ===============



    has_attached_file :coverphoto,
                :styles => {
                  :coverbar => "600x300>", :medium => "250x250^" , :thumb => "100x100^"},
                  #:source_file_options =>  {:all => '-rotate "-90>"'},
                  :storage => :s3,
                  :s3_credentials => "#{Rails.root}/config/s3.yml",
                  :bucket => "backpackbug",
                  :path => "/:style/:id/:filename"                


# ===============
# = Validations =
# ===============

validates :title, presence: true, length: { minimum: 6, maximum: 66 }
validates :body,  presence: true, length: { minimum: 10 }
validates :blogger_id, presence: true



# =================
# = Associations =
# =================    

belongs_to :blogger, :polymorphic => true
has_many :location_post
has_many :locations, :through => :location_post
belongs_to :profile
accepts_nested_attributes_for :locations, :allow_destroy => true, :reject_if => proc { |attributes| attributes['name'].blank? }

end end

【问题讨论】:

  • 我没有看到任何hidden_field,您可以在该字段出现的位置发布查看代码吗?此外,您的 form_for 块末尾似乎有两个 ends,我认为这只是一个复制错误。
  • 嗨@shioyama,是的,两个“端”是复制错误,抱歉。隐藏字段是由我正在使用的“嵌套表单”gem 添加的,并且似乎是它确定要删除哪个字段的方式。我在上面添加了一个渲染的 html 的 sn-p。还有其他想法吗?

标签: ruby-on-rails ruby-on-rails-3 forms destroy


【解决方案1】:

这个和另一个答案的组合解决了这个问题,在这里找到:

How can I fix this create function?

短期修复是添加 attr_accessible :_destroy 和 attr_accessor :_destroy。

谢谢两位!

【讨论】:

    【解决方案2】:

    :_destroy 添加到您的attr_accessible 列表中

    attr_accessible ...., :_destroy
    

    【讨论】:

    • 您好,谢谢您,但是我已经尝试过了,但仍然遇到同样的错误。它不是表格列,所以我认为它不应该尝试保存破坏属性。还有其他想法吗?
    • @JamesOsborn 您将 attr_accessible :_destroy 添加到哪个模型?
    • 嗨,Pavel,我将它添加到 post.rb 和 location.rb 中没有用,恐怕。还有其他想法吗?
    【解决方案3】:

    你应该写信给 post.rb,

     attr_accessible: locations_atributes
    

    accepts_nested_attributes_for :locations, :allow_destroy => true
    

    当您通过 post 对象更新位置对象时。

    【讨论】:

    • 您好,感谢您的评论。抱歉,我没有发布 post.rb,但它确实包含此内容。我现在已经发布了。还有其他建议吗?
    • 我宁愿建议你用rails控制台试试这一切,看看问题是真的出在关联上还是出在视图上。还要检查网络日志。
    【解决方案4】:

    替换 f.hidden_field 它必须保持不变(第 2 行)

     module ApplicationHelper
      def link_to_remove_fields(name, f)
        text_field_tag(:_destroy) + link_to_function(name, "remove_fields(this)")
      end
    

    【讨论】:

      猜你喜欢
      • 2012-10-25
      • 2011-09-04
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多