rails 3.1.0 belongs_to ActiveResource no longer working

早过忘川 提交于 2019-12-05 07:22:34

I didn't like the monkey patch so I created a module that I will include at initialization to extend ActiveRecord

module BelongsToActiveResource

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

    def ar_belongs_to( name, options = {} )
      class_eval %(
        def #{name}
          @#{name} ||= #{options[:class_name] || name.to_s.classify }.find( #{options[:foreign_key] || name.to_s + "_id" } )
        end

        def #{name}=(obj)
          @#{name} ||= obj
          self.#{ options[:foreign_key] || name.to_s + "_id" } = @#{name}.#{ options[:primary_key ] || 'id' }
        end
      )
    end

  end

end   

ActiveRecord::Base.class_eval { include BelongsToActiveResource }

Then in each ActiveRecord model would look like:

 #task.rb
 class Task < ActiveRecord::Base
   ar_belongs_to :employee
 end

Hope this helps someone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!