代码之家  ›  专栏  ›  技术社区  ›  zanona oldmanwiggins

RubyonRails-重写关联id创建过程

  •  0
  • zanona oldmanwiggins  · 技术社区  · 15 年前

    我正在尝试重写rails对关联对象应用和标识的方式,例如:

    有两种简单的模型:

    class Album < ActiveRecord::Base
      has_many :photos
    end
    
    class Photo < ActiveRecord::Base
      belongs_to :album
    end
    

    然后我想这样做:

    album = Album.new :title => 'First Album'
    album.photos.build
    album.save #=> true
    

    album_id 正在替换为我的自定义方法,而不是int,并且能够在保存之前进行转换。 但我想在Rails结构中全局地执行操作,因为它将是一种插件,我想让这个操作在动态模型上工作,这就是为什么我不能创建一个 before_save 模型验证。

    我不确定这是否容易理解,但我希望有人能在这方面帮助我。。

    SQLite3 DB http://cl.ly/1j3U/content

    所以你可以看到 它被替换为我的自定义ruby对象保存时…我已经禁用插件,然后它保存与记录11和12正常。。。

    我只想对rails操作进行操作,并用我的自定义方法进行转换,比如

    def rails_association_replaced_method(record)
       #take the record associations and apply a to_i custom method before save
       super(record)
    end
    

    我希望事情不要太复杂

    干杯

    2 回复  |  直到 15 年前
        1
  •  1
  •   zanona oldmanwiggins    15 年前

    如果我只重写activeRecord::Base save方法,那么如果处理得当,就可以执行该任务

    define_method 'save' do
      int_fields = self.class.columns.find_all { |column| column.type == :integer }
      int_fields.each do |field|
        if self.attributes[field.name]
          self.attributes[field.name] = self.attributes[field.name].to_i
        end
      end
      super
    end
    

        2
  •  0
  •   Joe Martinez    15 年前

    推荐文章