0

我需要引用user#role来定义模块中的关联。我已经尝试使用如下所示的块,但这不起作用。Rails 如何实现这样的行为?

class User < ActiveRecord::Base
  include Profile
  has_profile { |user| { class_name: "#{user.role}::Profile" }}
end

module Profile
  extend ActiveSupport::Concern

  module ClassMethods

    def has_profile(&block)

      role = ### How to access #role ? ###

      class_eval do
        has_one :profile, class_name: "#{role}::Profile"
      end
      ...
4

2 回答 2

0

你可能需要做这样的事情。我没有测试,我只是假设你可以做这种事情

class User < ActiveRecord::Base
  include Profile
  has_profile { |user| user.role }
end

module Profile
  extend ActiveSupport::Concern

  included do  
    after_initialize :_init_profile
  end

  def _init_profile
    role = @_role_block.call(self)
    # Here we do class eval on singleton so we dont change base class
    # I'm not sure if this works as it is but should be close enought
    class << self; self; end.class_eval do
      has_one :profile, class_name: "#{role}::Profile"
    end
  end


  module ClassMethods

    def has_profile(&block)
      @_role_block = block
      ...
于 2013-05-31T11:40:48.580 回答
0

这有效:

module Models
  module Profile
    extend ActiveSupport::Concern

    included do
      after_initialize :_init_profile
    end

    module ClassMethods
      def has_profile(&block)
        @profile_association_block = block
      end
    end

    def _init_profile
      block = self.class.instance_variable_get :@profile_association_block
      self.class.has_one :profile, block.call(self)
    end
于 2013-06-01T03:47:01.747 回答