2012-03-02 56 views
1

我試圖推出我自己的電子商務解決方案。使用Rails書籍擴展實用Web開發中解釋的軟件倉庫應用程序。共享2個模型的回形針附件

我目前正試圖找出附件。 本質上,我希望產品和Product_Variants使用Product_Shots來附加照片。 這可能會導致product_shots表的product_varariants值爲空值,因爲並非所有產品都有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 

回答

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 2012-03-03 05:22:02