Ruby 请教多态关联的验证问题

skywangxiaoshuai · 2016年11月18日 · 最后由 skywangxiaoshuai 回复于 2016年11月19日 · 1656 次阅读

现在有这样一个问题:企业模型(ent),产品模型(product)和一个图片模型(picture),要把企业的图片和产品的图片都存在同一张表中,模型层的关联如下:

图片模型:这个模型中的 photo 字段通过 paperclip 处理成了附件的形式,用来保存图片信息,photo 字段包含了图片的 size,url 等信息

class Picture < ApplicationRecord

  belongs_to :imageable, polymorphic: true

end

企业模型:

class Ent < ApplicationRecord

  has_many :pictures, as: :imageable, dependent: :destroy

end

产品模型:

class Product < ApplicationRecord

has_many :pictures, as: :imageable, dependent: :destroy

end

现在对产品图片的验证肯定是要放在产品模型中了,看资料有这样的一种关联验证:我试了一下不起作用,可能跟 as: :imageable 这个虚拟表有关系吧

class Product < ApplicationRecord

  has_many :pictures, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :pictures, allow_destroy: true, reject_if: proc { |attributes| attributes[:photo].blank? }

end

现在我需要限制产品图片的大小 10m 和限制每个产品的最多有 5 张图片,应该如何验证?

在普通的一对多关联中的图片验证是这样做的:logo 字段用来保存图片信息

has_attached_file :logo,
                    :styles => {s: "x100>", m: "x150>", l: "x200>", xl: "x300>"},
                    :default_style => :s,
                    :path => ":rails_root/public/system/:class/:id/:attachment/:style.:extension",
                    :url => "/system/:class/:id/:attachment/:style.:extension",
                    :default_url => "missing"

  #attributes validations
    validates_attachment :logo, content_type: { content_type: /\Aimage\/.*\z/ }, size: { in: 0..1.megabytes }

现在在多态中不知道该怎么搞了,求帮助。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号