【问题标题】:gem Paperclip interpolationgem 回形针插值
【发布时间】:2012-02-04 16:39:48
【问题描述】:

美好的一天。
我有导轨 3.1。和宝石回形针
在我管理公司合同的应用程序中:

MODEL    
    model/contract.rb
      has_many :contract_files

    model/contract_file.rb
      has_attached_file :data

CONSOLE
Loading development environment (Rails 3.1.0)

1.9.2p290 :001 > cont = Contract.first

  Contract Load (0.1ms)  SELECT "contracts".* FROM "contracts" LIMIT 1    
         => #Contract id: 1, organization: "Com.org", and etc ....

1.9.2p290 :002 > cont.contract_files

  ContractFile Load (0.2ms)  SELECT "contract_files".* FROM "contract_files"
     WHERE "contract_files"."contract_id" = 1     
         => #[ContractFile id: 88, caption: "asdf", and etc ...]

问题
好心,请告诉我,我怎样才能提取 Contract id: 1 in

model/contract_files.rb    
      has_attached_file :data,
      :url => "/assets/paperclip/:contract_id/:filename"

我想获得的示例
在 http//localhost:3000/contracts/1 上获取此类文件路径: http://localhost:3000/contracts/1/assets/paperclip/1/XXX.pdf http//localhost:3000/contracts/1/assets/paperclip/1/XXY.pdf http://localhost:3000/contracts/1/assets/paperclip/1/XXZ.pdf

非常感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.1 paperclip interpolation


    【解决方案1】:

    如果我明白了,你可以这样做:

    Contract.find( params[:id] ).contract_files.map { |cf| cf.data.url }
    # Dont't forget to handle nonexistent id
    

    更新

    要将 contract_id 放在 url 中,您应该以这种方式恢复默认的回形针 :url 和 :path 参数:

    #model/contract_file.rb
    has_attached_file :data, :path => "public/contracts/:parent_id/assets/paperclip/:id.:extension", :url => "/contracts/:parent_id/assets/paperclip/:id.:extension"
    
    Paperclip.interpolates :parent_id do |a, s|
        a.instance.contract.id
    end
    

    【讨论】:

    • 1.9.2p290 :007 > cont.contract_files.map { |cf| cf.data.url} => ["/assets/paperclip/data/88/original/download.jpg?1328369668"] 但你可以看到仍然没有contract.id
    • ContractFile 定义中是否有belongs_to :contract 指令?
    • github.com/itsNikolay/sophia我推了,估计你会更方便。 :)
    • 不要分叉这个 :) 你的解决方案有效!我花了一整天的时间。非常感谢您的帮助!
    • 该死,捆绑安装正在进行中)))祝你好运)
    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 2016-04-12
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多