0

我通过关联获得了多态性

# a/m/documnet.rb
class Document < ActiveRecord::Base
 has_many :possessions, as: :belonging
 has_many :clients, :through => :possessions, :source => :owner, :source_type => 'Client'
end

在控制台中

Document.new.clients 
#=> []

在形式简单的视图中

= f.association :clients, as: :check_boxes, collection: Client.all

它没有问题。

--

当我想动态关联有很多资源时,问题就开始了

class Document < ActiveRecord::Base
  has_many :possessions, as: :belonging

  def self.possession_owner_classes
     [Client, SomethingElse]
  end
  possession_owner_classes.each do |possession_class|
    has_many possession_class.model_name.underscore.pluralize, :through => :possessions,  :source => :owner, :source_type => possession_class.model_name
  end
end

在控制台中

Document.new.clients 
#=> []

在形式简单的视图中

= f.association :clients, as: :check_boxes, collection: Client.all

会抛出

Association :clients not found

所以 Rails 知道这种关联,但简单的形式不知道:-/ 有什么想法吗?

4

1 回答 1

1

好的,我发现了错误,

has_many possession_class.model_name.underscore.pluralize, :through => :possessions,  :source => :owner, :source_type => possession_class.model_name

应该

has_many possession_class.model_name.underscore.pluralize.to_sym, :through => :possessions,  :source => :owner, :source_type => possession_class.model_name

所以关联名称必须是符号而不是字符串

 :clients   # ok
 'clients'  # will blow up

呵呵:-\

于 2012-09-10T09:07:09.927 回答