product_picture.rb 2.8 KB

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