2012-03-02 24 views
1

私は自分のeコマースソリューションを展開しようとしています。 Pragmatic Web Development in Railsの本で説明したデポアプリケーションの拡張。2つのモデルで共有されているペーパークリップ添付

現在、添付ファイルを把握しようとしています。 基本的に、ProductとProduct_VariantsはProduct_Shotsを添付写真に使用します。 これは、すべての製品にprodcut_variantsがあるわけではないため、product_variantsの値が空のproduct_shotsテーブルになる可能性があります。これを実装するためのより良いアプローチはありますか?

商品モデル:

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 

答えて

2

もし私がこれを実装しようとするなら、私はそれを多相関係として行うと思います。だから、product.rbとproduct_variant.rbで:

has_many :product_shots, :dependent => :destroy, :as => :pictureable 

そしてproduct_shot.rbで

:今すぐ

belongs_to :pictureable, :polymorphic => true 

のいずれかの製品とproduct_variantは、彼らが好きなだけ(またはわずか)product_shotsを持っている、とすることができますどちらもproduct.product_shotsproduct_variant.product_shotsとしてアクセス可能です。データベースを正しく設定するようにしてください。product_shotsテーブルにはpictureable_typeとpictureable_idが必要です。

+0

が完璧です。私はそれをアタッチャブルと呼んだだけです。どうもありがとうございました! – frishi

関連する問題