Your posts match “ rails ” tag:

inu.cc 开发日志

这个礼拜的开发基本上都以 JavaScript 为主,实现一个类似于 bluedot.us 的收藏对话框功能。因为要在未知的页面中插入 JavaScript ,所以还是碰到了很多问题。包括 JavaScript 的字符编码、各个页面不同的 DOCTYPE 声明导致的盒模型解析问题、从 inu.cc 载入脚本、跨域提交、callbacks 等等,都比想象的复杂的多。

特别是跨域提交的问题,至今仍然没有搞清除 bluedot.us 是怎么实现的,不得不佩服他们的技术实力。

当然,在这个过程当中也学会了一些技巧,以后写 js 的时候肯定会派上用场的

扩展 Paperclip

Paperclip 是 Rails 的一个处理 attachment 的插件,相对于以往的 FileColumn 在灵活性和效率上更胜一筹,而且代码也比较好看。这个视频 简单的介绍了 Paperclip 的使用方法。

默认的设置,URL 的占位符中与模型本身相关的只有 id,但是一些情况下,你可能会更希望以其他形式来组织你的附件目录 - 比如以 SKU 来代替数据库记录的 id。这里我们暂不讨论这种做法的好坏,双方面的,好处是目录结构更具有维护性,坏处是万一以后升级数据库,SKU 加个前缀什么的……

Here we go!

使用 paperclip 需要在 model 中调用 has_attached_file 方法,检查文档,有一些简单的使用样例,但是没有我们需要的。通过方法描述我们知道这个方法建立了一个 Paperclip::Attachment 对象,我们继续看文档。对象的方法很少,首先思考:应为我们需要配置的是 attachment 的 url 规则,那么应当是对应整个类而不是单个实例,因此我们只关注 Peperclip::Attachment 的类方法,只有两个。default_options 没有描述,而且展开代码发现并不是我们需要的。

Paperclip::Attchment.interpolation

A hash of procs that are run during the interpolation of a path or
url. A variable of the format :name will be replaced with the return
value of the proc named “:name”. Each lambda takes the attachment and
the current style as arguments. This hash can be added to with your own
proc if necessary.

这正是我们需要的,接下来的扩展就非常方便了:

# app/models/product.rb  

class Product < ActiveRecord::Base  
  has_attached_file :photo,  
    :style => { :thumb => '64x64>' },  
    :url => '/images/products/:to_param.:extension'  
    
  def to_param  
    return self.sku  
  end  
end  
  
# config/initializers/paperclip.rb  

Paperclip::Attachment.interpolations.merge!(  
  :to_param => lambda { |attachment, style| attachment.instance.to_param }  
)

在这里不直接使用 :sku 作为占位符而使用 :to_param 是为了在其他模型中更加的灵活。