【问题标题】:How to get the value of the attr_accessible within model class Rails + Paperclip如何在模型类 Rails + Paperclip 中获取 attr_accessible 的值
【发布时间】:2015-04-16 23:02:49
【问题描述】:

我正在尝试为要上传到我的 mp3 对象设置一些元数据

AWS S3 through Rails 使用回形针。

class myClass < ActiveRecord::Base
    attr_accessible :mp3, file_name
    attr_accessor :mp3, file_name

    has_attached_file :mp3,
        // some s3 credential info + bucket
        :s3_metadata => {
            :name => //get the name attr of the instance that I'm trying to save
        }

这在 Model.rb 文件中。

问题是,如果我想将元数据设置为该实例具有的某个属性,

如何在此处访问该值?

【问题讨论】:

    标签: ruby-on-rails paperclip


    【解决方案1】:

    ActiveRecord::Base 类的对象调用 .attributes 将返回所有属性的哈希值。

    在这种情况下,您也许可以使用 lambda,类似于

    name: ->{ method_that_returns_the_name }
    

    可能不会在类声明中设置文件名。你试过了吗

    @object.file_name = 'My File Name'
    @object.save
    

    如果您想从其他地方获取名称,可以使用过滤器。

    before_save do 
      self.file_name = "image-#{self.id}"
    end
    

    【讨论】:

    • 但我如何在模型类本身中做到这一点?
    • 您只是想更改文件名吗?
    • 我已经编辑了这个问题。所以基本上在回形针的'has_attached_file'中,我想将元数据设置为这个模型的'file_name'属性。
    • 那你知道创建实例后我可以使用什么回形针方法来设置S3元数据吗?
    • 你试过写@object.file_name = 'New File Name'吗?
    【解决方案2】:

    要在您的示例中完成此操作,您可以使用:

    class myClass < ActiveRecord::Base
        attr_accessible :mp3, file_name
        attr_accessor :mp3, file_name
    
        has_attached_file :mp3,
            // some s3 credential info + bucket
            s3_headers: lambda { |attachment|
              { 'x-amz-meta-name' => attachment.instance.name }
            }
    

    看起来 s3_metadata 不会使用 proc,但您可以使用 s3_headers 代替,方法是在标头前加上“x-amz-meta-”。您可以通过 lambda 中的 attachment.instance 访问“myClass”的实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      相关资源
      最近更新 更多