我的回购:https://github.com/Gtar69/artstore_hw2
我想在某些产品中实现上传超过1张照片。 基本的想法是管理员进入产品的编辑页面,并且可以上传新照片"对于某些产品。我在"如何在编辑页面中创建照片对象并将此照片对象添加到产品中。 !我无法在编辑页面中成功创建照片对象.....
非常感谢
在view / admin / products / edit.html.erb
中<h2> 編輯 <%= @product.title %> </h2>
<%= simple_form_for [:admin, @product ] , :html => { :class => "form form-horizontal" } do |f| %>
<div class="form-group">
<div class="col-sm-10">
<%= f.input :title %>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<%= f.input :description, :as => :text %>
</div>
</div>
<div class="form-group">
<div class="col-sm-1">
<%= f.input :quantity %>
</div>
</div>
<div class="form-group">
<div class="col-sm-1">
<%= f.input :price %>
</div>
</div>
<!-- 20140623 upload more than one photo feature added -->
<div>
<%= simple_form_for [:admin, @product, @product.photos.build] do |f| %>
<%= f.input :image , :as => :file %>
<div class="form-group">
<%= f.submit "upload new photos", :class => "btn btn-default" , :disable_with => 'Submiting...' %>
</div>
<%end%>
</div>
<div class="form-group">
<%= f.submit "Submit", :class => "btn btn-default" , :disable_with => 'Submiting...' %>
</div>
<% end %>
在controllers / admin / products_controller.rb
中 def edit
@product = Product.find(params[:id])
#@photo = @product.photos.build
#@product.add_photo_to_product(@photo)
end
在controllers / admin / photos_controller.rb
中 def create
#binding.pry
@product = Product.find(params[:product_id])
@photo = @product.photos.create(photo_params)
@product.add_photo_to_product(@photo)
redirect_to admin_products_path
end
private
def photo_params
params.require(:photo).permit(:image)
end
in model / product.rb
class Product < ActiveRecord::Base
has_many :photos
accepts_nested_attributes_for :photos
validates :title , :presence => true
validates :quantity , :presence => true
def default_photo
photos.first
end
def add_photo_to_product(photo)
photos << photo
end
端
in photos.rb
class Photo < ActiveRecord::Base
belongs_to :product
mount_uploader :image, ImageUploader
end