2012-03-02 2 views
1

Я пытаюсь создать собственное решение для электронной коммерции. Расширение приложения депо, описанного в книге Pragmatic Web Development with Rails.Приложение для переноски скрепки, используемое двумя моделями

В настоящее время я пытаюсь найти вложения. По сути, я хочу, чтобы 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 

ответ

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_shots и product_variant.product_shots. Просто убедитесь, что вы настроили свою базу данных правильно - для вашей таблицы product_shots вам понадобятся функции pictureable_type и pictureable_id.

+0

безупречный. Только я назвал это прикрепляемым. Большое спасибо! – frishi