【问题标题】:rails model callbacksrails 模型回调
【发布时间】:2010-12-11 19:02:32
【问题描述】:

如何根据模型是创建还是更新记录在模型内部执行某些操作?我敢肯定这真的很简单,但我似乎无法弄清楚。

这些是使用回形针更新或创建附件的不同样式。

class Photo < ActiveRecord::Base

  belongs_to :product

  #after_upate :flag_somthin

  Paperclip.interpolates :product_id  do |attachment, style|
    attachment.instance.product_id
  end

  has_attached_file :data,
    :storage => 's3',
    :s3_credentials => "#{RAILS_ROOT}/config/s3_credentials.yml",
    :bucket => 'leatherarts.com',
    :s3_host_alias => 'leatherarts.com.s3.amazonaws.com',
    :url => ':s3_alias_url',
    :path => "images/products/:product_id/:style/:basename.:extension",
    :styles => lambda { |style| style.instance.choose_styles },
    :default_style => :medium,
    :default_url => 'http://leatherarts.com.s3.amazonaws.com/images/records/m1.png',
    :s3_headers => { 'Expires' => 2.months.from_now.httpdate }

    validates_attachment_presence :data
    validates_attachment_size :data, :less_than => 10.megabytes
    validates_attachment_content_type :data, :content_type => ['image/jpeg','image/gif','image/png']

    def choose_styles
      { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>", :backup => "2000x2000>" }, :on => :create
      { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>" }, :on => :update
    end

end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 model callback


    【解决方案1】:

    使用new_record? 方法返回不同的哈希值:

    def choose_styles
      defaults = { :thumb => "60x60#", :small => "200x200>", :medium => "400x400>", :large => "1000x1000>" }
      defaults.merge! :backup => "2000x2000>" if new_record?
      defaults
    end
    

    【讨论】:

    • 是的,这就是我通常会做的事情,但我不确定在这种情况下如何完成它,我更新了我的问题并提供了更多细节。
    • 为什么要通过多次更新保留原始照片?这听起来应该存储在不同的记录中。
    猜你喜欢
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多