我有旧版数据库
我想使用回形针宝石上传图片
回形针需要四个参数才能工作
但是我只有一个字段,即文件名,其余所有参数不在数据库中
那么我如何使用单个参数集成回形针
以下是我在模型中的代码

class ItemMaster < ActiveRecord::Base

  set_table_name "MDIMT"

  attr_accessible :IMTNAME, :IMTBRIEFDESC, :IMTDETAILDESC, :IMTIMAGE, :IMTCALORIE, :IMTIMTEMCODE1, :IMTIMTEMCODE2,
                  :IMTPRICE, :IMTISVARPRICE, :IMTISCUSTOMIZED, :IMTDURATIONMINS, :IMTSEQNUM, :CREATEDBY, :MODIFIEDBY,
                  :CREATEDATE, :MODIFYDATE, :EXTRAFIELD1, :EXTRAFIELD2, :EXTRAFIELD3, :EXTRAFIELD4, :IMTISACTIVE, :IMTTAX1,
                  :IMTTAX2, :IMTTAX3, :IMTTAX4, :IMTCNDITEMTYPE, :IMTCNDFILTEROPT
  alias_attribute :image_file_name, :IMTIMAGE
  has_attached_file :image,
                    :path => ":rails_root/public/assets/:basename.:extension",
                    :url => "/assets/images/:basename.:extension"
end

最佳答案

回形针使用标准的获取器和设置器来存储或接收来自实例的值。您云尝试使getter和setter过载,而是将数据存储在序列化的哈希中:

class ItemMaster < ActiveRecord::Base
  set_table_name "MDIMT"

  attr_accessible :IMTNAME, :IMTBRIEFDESC, :IMTDETAILDESC, :IMTIMAGE, :IMTCALORIE, :IMTIMTEMCODE1, :IMTIMTEMCODE2,
                  :IMTPRICE, :IMTISVARPRICE, :IMTISCUSTOMIZED, :IMTDURATIONMINS, :IMTSEQNUM, :CREATEDBY, :MODIFIEDBY,
                  :CREATEDATE, :MODIFYDATE, :EXTRAFIELD1, :EXTRAFIELD2, :EXTRAFIELD3, :EXTRAFIELD4, :IMTISACTIVE, :IMTTAX1,
                  :IMTTAX2, :IMTTAX3, :IMTTAX4, :IMTCNDITEMTYPE, :IMTCNDFILTEROPT

  alias_attribute   :image_hash, :IMTIMAGE
  default_value_for :image_hash, {}
  serialize         :image_hash, Hash

  has_attached_file :image,
                    :path => ":rails_root/public/assets/:basename.:extension",
                    :url => "/assets/images/:basename.:extension"

  %w[ image_file_name image_file_size image_content_type image_processing image_updated_at ].each do |field|

    # Adds getter and setter for all keys in the array and stored the data in the image_hash instead
    class_eval <<-END_OF_RUBY, __FILE__, __LINE__ + 1

      def #{field}
        image_hash['#{field}']
      end

      def #{field}=(value)
        self.image_hash['#{field}'] = value
      end

    END_OF_RUBY
  end
end

关于mysql - 回形针与遗留数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20242467/

10-16 07:11