使用未在模型中引用的表:join_table

时间:2013-06-01 15:44:45

标签: ruby-on-rails ruby-on-rails-3.2

有可能吗?我有点迷失了。

我正在尝试将一些功能添加到我没有开发的Ryby on Rails 3.2应用程序上,但我对模型定义感到困惑。

以下是示例:

    class Indicator < ActiveRecord::Base
      #attr_accessible :name, :objective_ids, :weight, :operation_id, :objective_id,         :unit, :formula, :acronym
      attr_protected
      has_and_belongs_to_many :objectives

      has_many :indicator_scores
      has_many :indicatorscores, :class_name => 'IndicatorScore', :foreign_key =>         "scoredate_id"
      belongs_to :operation

      belongs_to :objective

      has_and_belongs_to_many :sons, :join_table => "indicator_father_son",    :class_name => "Indicator", :foreign_key => "indicatorfather_id", :association_foreign_key => "indicatorson_id"


    end

在此模型中,特别是在 has_and_belongs_to_many 选项中,我已经交叉了想法,因为表“indicator_father_son”没有模型。

这在Ruby on Rails MVC惯例中是否合法?

has_and_belongs_to_many 子句与所有选项完全相同?为什么有必要?

如果模型展示不足以解决问题,我可以提供更多代码。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

来自:http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

“has_and_belongs_to_many关联创建了与另一个模型的直接多对多连接,没有介入模型。例如,如果您的应用程序包含组件和零件,每个组件包含许多零件,并且每个零件都出现在许多组件中,你可以用这种方式宣布模型。“

在这种情况下,原始编码器添加了一个:join_table子句,强制表名与指定值匹配。如果打开数据库,您将看到一个名为indicator_father_son的表。

同样,foreign_key和association_foreign_key会覆盖默认的外键名称。