1

我正在尝试推出自己的电子商务解决方案。扩展在 Pragmatic Web Development with Rails 一书中解释的 depot 应用程序。

我目前正在尝试找出附件。本质上,我希望 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

产品镜头模型(由回形针处理)

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
4

1 回答 1

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 才能工作。

于 2012-03-02T20:09:35.457 回答