我在这里关注了教程截屏: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'
我已经为帖子发布模型添加了所有属性的列表。像:
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
有人可以给我一些提示吗?非常感谢!
答案 0 :(得分:2)
您的Asset
模型也需要attr_accessible - 专门针对asset
字段。