2012-03-02 3 views
1

나는 자체 전자 상거래 솔루션을 출시하려고합니다. Pragmatic Web Development with Rails에 설명 된 저장소 응용 프로그램 확장.2 개의 모델이 공유하는 클립 클립 첨부

현재 첨부 파일을 찾으려고합니다. 기본적으로 제품 및 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

관련 문제