product_picture.rb 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. require 'uuid'
  2. class ProductPicture < ActiveRecord::Base
  3. has_paper_trail
  4. self.table_name = "product_pictures"
  5. after_commit :clear_product_cache
  6. after_destroy :after_destroy
  7. belongs_to :product
  8. validates :product_id, presence: true
  9. attr_accessor :v_img
  10. IMG_STORE_PATH = "product_pictures"
  11. PIC_TYPE_ENUM = [["详情图",1],["轮播图",0]]
  12. rails_admin do
  13. navigation_label '商品管理'
  14. weight -240
  15. list do
  16. filters [:id,:pic_type]
  17. field :id
  18. field :product
  19. field :img do
  20. formatted_value do
  21. bindings[:view].tag(:img,{:src => bindings[:object].get_img,
  22. :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
  23. :onClick => "javascript:window.open('#{bindings[:object].get_img}')"})
  24. end
  25. end
  26. field :pic_type,:enum do
  27. enum do
  28. PIC_TYPE_ENUM
  29. end
  30. end
  31. field :sort
  32. field :created_at
  33. field :updated_at
  34. end
  35. show do
  36. field :id
  37. field :product
  38. field :img do
  39. formatted_value do
  40. bindings[:view].tag(:img,{:src => bindings[:object].get_img,
  41. :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px;',
  42. :onClick => "javascript:window.open('#{bindings[:object].get_img}')"})
  43. end
  44. end
  45. field :pic_type, :enum do
  46. enum do
  47. PIC_TYPE_ENUM
  48. end
  49. end
  50. field :sort
  51. field :created_at
  52. field :updated_at
  53. end
  54. edit do
  55. field :product
  56. field :v_img, :file_upload do
  57. pretty_value do
  58. bindings[:view].tag(:img,{:src => bindings[:object].get_img, :class => 'preview'})
  59. end
  60. end
  61. field :pic_type,:enum do
  62. enum do
  63. PIC_TYPE_ENUM
  64. end
  65. end
  66. field :sort
  67. end
  68. end
  69. def v_img=file
  70. unless file.blank?
  71. # clear_img
  72. file_name = "#{UUID.new.generate[0...8].downcase}.jpg"
  73. file_path = "#{IMG_STORE_PATH}/#{file_name}"
  74. Ali::Oss.store(Ali::Oss::BUCKET_NAME_PUBLIC_READ, file_path, file.read)
  75. self.img = file_path
  76. self.save
  77. end
  78. end
  79. def clear_img
  80. file_path = "#{self.img}"
  81. Ali::Oss.delete_object(Ali::Oss::BUCKET_NAME_PUBLIC_READ,file_path)
  82. end
  83. def get_img
  84. url = "http://#{Ali::Oss::CDN_URL_FOR_HOST}/#{self.img}"
  85. return url
  86. end
  87. def after_destroy
  88. clear_img
  89. end
  90. def clear_product_cache
  91. Product.notify_product_cache(self.product_id)
  92. end
  93. end