0
無法理解在更新主模型時如何驗證關聯模型的大小。在我的應用程序產品中不能有超過6個附加圖像。每一個形象,我存儲類ProductAttachment如何在更新模型時驗證關聯對象的編號
product.rb
class Product < ActiveRecord::Base
belongs_to :user
has_many :product_attachments, dependent: :destroy
accepts_nested_attributes_for :product_attachments
validate :validate_attachments_count
def validate_attachments_count
if self.product_attachments.size > 6
errors.add(:product_attachments, 'Pic number should not be more than 6')
end
end
end
product_attachment.rb
class ProductAttachment < ActiveRecord::Base
mount_uploader :picture, PictureUploader
belongs_to :product
after_destroy :delete_picture
private
def delete_picture
self.remove_picture!
end
end
和products_controller我有一個創建方法
def create
@product = current_user.products.new(products_params)
# if pics available add attachments
if params[:product_attachments] != nil
params[:product_attachments]['picture'].each do |p|
@product_attachment = @product.product_attachments.build(:picture => p)
end
end
if @product.save
flash[:success] = 'Product created.'
redirect_to [current_user, @product]
else
flash[:danger] = 'Product not created'
render 'new'
end
end
的正常工作和創建拒絕,如果我嘗試將超過6張圖片,但更新方法不能確定atachments的數量在某種程度上,並允許添加的圖片的任何數字
def update
if @product.update_attributes(products_params)
if params[:product_attachments] != nil
params[:product_attachments]['picture'].each do |p|
@product_attachment = @product.product_attachments.create(:picture => p)
end
end
flash[:success] = 'Info updated.'
redirect_to [current_user, @product]
else
flash[:danger] = 'Can't update'
render :edit
end
end
我想我應該改變somemething products_params方法,但我不能想出究竟
def products_params
params.require(:product).permit(:name, :width, :height, :depth, :color, :price, :category, :description,
product_attachments_attributes: [:id, :product_id, :picture, :remove_picture])
end
這是一種形式
<div class="form-group">
<% if @product.new_record? %>
<%= f.fields_for :product_attachments do |p| %>
<div class="control-label col-md-4">
<%= p.label :picture, 'Pictures' %>
</div>
<div class="col-md-4">
<%= p.file_field :picture, multiple: true, name: 'product_attachments[picture][]' %>
</div>
<% end %>
<% else %>
<div class="control-label col-md-4"><strong>Pictures</strong></div>
<div class="col-md-4">
<% @product.product_attachments.each do |p| %>
<%= image_tag p.picture_url, class: 'pic' %>
<%= link_to 'Delete', product_attachment_path(p),
method: :delete , data: { confirm: 'Sure?'} %>
<% end %>
<%= f.fields_for :product_attachments, @product.product_attachments.new do |p| %>
<div class="col-md-4">
<%= p.file_field :picture, multiple: true, name: 'product_attachments[picture][]' %>
</div>
<% end %>
</div>
<% end %>
</div>