Rails 关于 build 的问题

yeyong14 · 2013年11月25日 · 最后由 yeyong14 回复于 2013年11月26日 · 2261 次阅读

有两个模型productphoto, 已经做好了关联

#product.rb
has_many :photos
accepts_netsted_attributes_for :photos


#photo.rb
belongs_to :product

在控制器定义了

....
def new
@product = Product.new
@product.photos.build
.
....

这个@product.photos.build 好像可以上传一张图片,现在我就想上传多张图片。这个应该要怎么做的,请教各位大牛。

n.times { @product.photos.build }

accepts_nested_attributes_for

@Martin91 回复好快啊。真是非常感谢。这个我试过了。如果我要上传 8 张图片。也就是

8.times { @product.photos.build }

但在form表单中就出现了 8 个上传的按钮,这样很不美观,想用jQuerydelegate的函数动态添加上传的数目。 不知有什么好的思路

@shooter 这个也是添加了的

#3 楼 @yeyong14 出现 8 个上传的按钮?你把你的 view 代码贴上来看下吧

@Martin91

#控制器
def new
    @product = Product.new
                8.times{@product.pictures.build}
                @product.videos.build
end

#View

<%= form_for(@product, html: {multipart: true}) do |f| %>
<div class="field">
                <%= f.fields_for :pictures do |pic| %>
                        <%= pic.label :imag %>
                        <%= pic.file_field :image %>
                <% end %>
  </div>
<% end %>

@song940 谢谢。刚刚是看到你的帖子,我正在试

@song940 @Martin91我按照你给博客地址配置了可以动态添加项目。就是更新的时候出现了这个错误

NoMethodError in ProductsController#update

undefined method `file_changed?' for #<Photo:0xb5eee250>

当 photos 为空的时候。能正常更新。当有项目的时候就报上面的错。

@song940 @Martin91 控制器报错的位置

app/controllers/products_controller.rb:61:in `block in update'
app/controllers/products_controller.rb:60:in `update'

#controller
def update
  @product = Product.find(params[:id])
  if @product.update_attributes(params[:product])
   redirect_to @product
  else 
   render 'edit'
end

update_attributes(:product => params[:product]) or update(params)

@song940 现在出现了这个错误

ActiveModel::MassAssignmentSecurity::Error in ProductsController#update

Can't mass-assign protected attributes: product
需要 登录 后方可回复, 如果你还没有账号请 注册新账号