1

我在这里按照教程截屏:http ://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads 。我希望我的模型显示多张图片上传。

我仔细检查了每个步骤,最常见的问题是忘记将 assets_attributes 添加到 attr_accessible,我已经做到了。另一个问题可能是忘记将 ID 添加到资产模型,我也这样做了。但是,我仍然无法理解为什么会发生这种情况。

Can't mass-assign protected attributes: asset in app/controllers/posts_controller.rb:24:in `update'

我已经为 Post to post 模型添加了所有属性的列表。像:

class Post < ActiveRecord::Base
  attr_accessible :name, :content, :assets_attributes 
  validates :user_id, presence: true
  belongs_to :user
  has_many :assets
  accepts_nested_attributes_for :assets, :allow_destroy => true
  default_scope order: 'posts.created_at DESC'
 end

这是 post_controller.rb 文件:

 def edit
    @post = Post.find(params[:id])
    5.times { @post.assets.build }
 end
 def update
    @post = Post.find(params[:id])
    if @post.update_attributes(params[:post])      
          redirect_to @post, :notice => "Post has been updated."
 end
def create
    post = current_user.posts.build(params[:post])
    if post.save
        flash[:success] = "post created success!"
        redirect_to @post
    else
        @feed_items = []
        flash[:failure] = "post created fail!"
        redirect_to root_path
    end
 end
 def new
    @post = current_user.posts.new #if signed_in?
    5.times { @post.assets.build }
 end

这是模板文件:

        <%= simple_form_for(@post, :html => {:multipart => true})  do |f| %>
           <%= f.label :name %>
           <%= f.text_field :name %>
           <%= f.label :content %>
           <%= f.text_field :content %>
           <%= f.simple_fields_for :assets, :html => { :multipart => true } do |asset_fields| %>
               <% if asset_fields.object.new_record? %>
                   <P><%= asset_fields.file_field :asset %> </P>
               <% end %>
           <% end %>
            <%= f.simple_fields_for :assets, :html => { :multipart => true } do |asset_fields| %>
               <% unless asset_fields.object.new_record? %>
                  <P><%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.objects.asset.url(:original) %>
                     <%= asset_fields.check_box :_destroy %></P>
               <% end %>
           <% end %>

下面是asset.rb:

    class Asset < ActiveRecord::Base
      belongs_to :post
      has_attached_file :asset,
                :style => { :large => "640x480", :medium => "300x300", :thumb => "100x100"} ,
                :path => ":rails_root/public/system/posts/images/:id/:style/:filename",
                :url => "/system/posts/images/:id/:style/:filename"
    end

有人可以给我一些提示吗?非常感谢!

4

1 回答 1

2

您的Asset模型也需要具有 attr_accessible - 特别是针对该asset字段。

于 2012-11-26T08:01:26.093 回答