1

我了解如何使用活动目录中的 class_name 选项来引用命名空间模型:

has_one :slide, :class_name => '::Refinery::Slides::Slide'

以及如何使用多态关联

has_one :slide, :as => :slideable

你可以一起使用它们吗?

has_one :slide, :class_name => '::Refinery::Slides::Slide', :as => :slideable

如果是这样,你如何定义多态关联?

belongs_to :slideable, :polymorphic => true, class_name='::Refinery::Slideables::Slideable' #NO   

我正在使用 RefineryCMS,您添加的每个引擎都在 Refinery::PluralModel::SingularModel 中命名。基本上,我希望能够将幻灯片与案例研究或工作相关联。以下是实际模型。

module Refinery
  module CaseStudies
    class CaseStudy < Refinery::Core::BaseModel
      attr_accessible :title, :description, :position
      has_one :slide, :class_name => '::Refinery::Slides::Slide', :as => :slideable
    end
  end
end

module Refinery
  module Works
    class Work < Refinery::Core::BaseModel
      attr_accessible :title, :description, :position, 
      has_one :slide, :class_name => '::Refinery::Slides::Slide', :as => :slideable
    end
  end
end

module Refinery
  module Slides
    class Slide < Refinery::Core::BaseModel
      attr_accessible :slide_id, :caption, :position, :slideable_id, :slideable
      belongs_to :slide, :class_name => '::Refinery::Image'
      belongs_to :slideable, :polymorphic => true
    end
  end
end

似乎我应该可以说 slide.slideable.title 但我收到一个错误:nil:NilClass 的未定义方法“标题”

apidoc指定 inverse_of 不能与多态一起使用,但对 class_name 只字未提

4

1 回答 1

0

要使多态关联起作用,您需要在模型上添加一个类型列和一个 id 列,该列“属于”另一个。类型列将存储类名,因此无需在通用关联中指定。

例如, aComment可以属于 aQuestion或 an Answer。让我们称问题和答案为“可评论的”。评论应该有:commentable_id和列:commentable_type

class Comment < ActiveRecord::Base
  # has columns :commentable_id and :commentable_type
  belongs_to :commentable, :polymorphic => true
end

class Question < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Answer < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

# example
comment = Comment.new(:body => "Nice answer!")
comment.commentable = Answer.find(1)
comment.save

因此,在您的情况下,您可以从and中删除:class_name选项,并确保将列(to go with ) 和(to go with ) 添加到您的. 它应该与命名空间的类名一起“正常工作”。WorkCaseStudy:slide_type:slide_id:slideable_type:slideable_idSlide

module Refinery
  module CaseStudies
    class CaseStudy < Refinery::Core::BaseModel
      attr_accessible :title, :description, :position
      has_one :slide, :as => :slideable
    end
  end
end

module Refinery
  module Works
    class Work < Refinery::Core::BaseModel
      attr_accessible :title, :description, :position, 
      has_one :slide, :as => :slideable
    end
  end
end

module Refinery
  module Slides
    class Slide < Refinery::Core::BaseModel
      attr_accessible :slide_id, :caption, :position, :slideable_id, :slideable
      # add :slide_type and :slideable_type columns
      belongs_to :slide, :polymorphic => true
      belongs_to :slideable, :polymorphic => true
    end
  end
end
于 2013-04-24T01:54:30.130 回答