我正在尝试推出自己的电子商务解决方案。扩展使用Rails的Pragmatic Web Development中解释的软件仓库应用程序。
我目前正试图找出附件。 基本上我希望Product和Product_Variants使用Product_Shots来附加照片。 这可能会导致product_shots表的product_variants值为空,因为并非所有产品都有prodcut_variants。有没有更好的方法来实现这个?
产品型号:
class Product < ActiveRecord::Base
validates :title, :description, :price, :presence=>true
validates :title, :uniqueness => true
validates :price, :numericality =>{:greater_than_or_equal_to => 0.01}
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
has_and_belongs_to_many :product_categories
has_many :product_variants
has_many :product_shots, :dependent => :destroy
accepts_nested_attributes_for :product_shots, :allow_destroy => true,
:reject_if => proc { |attributes| attributes['shot'].blank?
}
private
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, "Line items present")
end
end
end
产品变体型号
class ProductVariant < ActiveRecord::Base
belongs_to :product
belongs_to :product_categories
has_many :variant_attributes
has_many :product_shots # can I do this?
end
产品拍摄模型(由Paperclip处理)
class ProductShot < ActiveRecord::Base
belongs_to :product, :dependent =>:destroy
#Can I do this?
belongs_to :product_variant, :dependent => :destroy
has_attached_file :shot, :styles => { :medium => "637x471>",
:thumb => Proc.new { |instance| instance.resize }},
:url => "/shots/:style/:basename.:extension",
:path =>":rails_root/public/shots/:style/:basename.:extension"
validates_attachment_content_type :shot, :content_type => ['image/png', 'image/jpg', 'image/jpeg', 'image/gif ']
validates_attachment_size :shot, :less_than => 2.megabytes
### End Paperclip ####
def resize
geo = Paperclip::Geometry.from_file(shot.to_file(:original))
ratio = geo.width/geo.height
min_width = 142
min_height = 119
if ratio > 1
# Horizontal Image
final_height = min_height
final_width = final_height * ratio
"#{final_width.round}x#{final_height.round}!"
else
# Vertical Image
final_width = min_width
final_height = final_width * ratio
"#{final_height.round}x#{final_width.round}!"
end
end
end
答案 0 :(得分:2)
如果我要实现这一点,我想我会把它作为一种多态关系。所以在product.rb和product_variant.rb中:
has_many :product_shots, :dependent => :destroy, :as => :pictureable
在product_shot.rb中:
belongs_to :pictureable, :polymorphic => true
现在,product和product_variant可以拥有他们想要的尽可能多(或很少)的product_shot,并且可以product.product_shots
和product_variant.product_shots
访问。只需确保正确设置数据库 - 您的product_shots表需要pictureable_type和pictureable_id才能使用。