0

Is is possible to do? I'm kinda lost with this.

I'm trying to add some functionality to a Ruby on Rails 3.2 app that I did not develop but I am confused with the model definitions.

Here is and example:

    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

In this Model, specially on the has_and_belongs_to_many option I have crossed thoughts because the table "indicator_father_son" doesn't have a model.

Is this legal in Ruby on Rails MVC convention?

What does the has_and_belongs_to_many clause with all the options exactly do? and why is it necessary?

I can provide more code if the model show is not enough to grasp the issue.

Thanks in advance for any help.

4

1 回答 1

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 会覆盖默认的外键名称。

于 2013-06-01T17:06:57.560 回答