我有模型产品和产品图片. Product_images是一种回形针模型.产品有很多product_images.我正在制作一个Active Admin表单,上传多个图像并将这些图像显示在Products视图页面上.
但是,当我保存产品时.产品表已更新,但不是product_image表.图像正常附加,但我无法更新已上传图像的字段.
class Product < ActiveRecord::Base attr_accessible :name,:product_images_attributes has_many :product_images,:dependent => :destroy accepts_nested_attributes_for :product_images,:reject_if => lambda { |t| t['product_image'].nil? },:allow_destroy => true end class Productimage < ActiveRecord::Base attr_accessible :name,:style attr_accessible :image belongs_to :product has_attached_file :image,:styles => { :small => "150x150>",:large => "320x240>" } validates_attachment_presence :image end ActiveAdmin.register Product do form :html => { :multipart => true } do |f| f.inputs "Admin Details" do f.input :name end f.inputs "Product images" do f.has_many :product_images do |p| p.input :style,:as => :select,:collection => Image::STYLES,:include_blank => false p.input :image,:as => :file,:label => "Image",:hint => p.object.image.nil? ? p.template.content_tag(:span,"No Image Yet") : p.template.image_tag(p.object.image.url(:small)) p.input :_destroy,:as=>:boolean,:required => false,:label => 'Remove image' end end f.buttons end
UPDATE
在产品模型中我做:
after_update :check def check if Productimage.find_by_product_id(self.id).changed? raise "image" else raise "fail" end end
它总是提高“失败”
解决方法
您可以通过添加以下内容将ActiveRecord配置为级联保存对模型集合中项目的更改:autosave =>声明关联时的true选项.
尝试:
has_many :product_images,:dependent => :destroy,:autosave => true
此外,您可以在after_save回调中将表数据保存在关联中,如下所示:
class Product < ActiveRecord::Base attr_accessible :name,:allow_destroy => true after_save :do_product_image_update private def do_product_image_update self.product_images.save end end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。