Search code examples
ruby-on-railsruby-on-rails-3activerecordruby-on-rails-3.2belongs-to

Use through option on a belongs_to ActiveRecord association


Is there a way to use the through option in a belongs_to relationship? The Rails documentation on belongs_to doesn't mention through as an option, why not? I want to do something like the following:

class Lesson < ActiveRecord::Base
  attr_accessible :name, :lesson_group_id
  belongs_to :lesson_group
  belongs_to :level, through: :lesson_group
end

class LessonGroup < ActiveRecord::Base
  attr_accessible :name, :level_id
  belongs_to :level
  has_many :lessons
end

class Level < ActiveRecord::Base
  attr_accessible :number
  has_many :lesson_groups
end

Then I can do something like Lesson.first.level. Using latest stable Rails (3.2.9 as of now).


Solution

  • In the link you gave:

    Specifies a one-to-one association with another class. This method should only be used if this class contains the foreign key.

    I think you should use has_one :level, through: :lesson_group, like following:

    class Lesson < ActiveRecord::Base
      attr_accessible :name, :lesson_group_id
      belongs_to :lesson_group
      has_one :level, through: :lesson_group
    end
    
    class LessonGroup < ActiveRecord::Base
      attr_accessible :name, :level_id
      belongs_to :level
      has_many :lessons
    end
    
    class Level < ActiveRecord::Base
      attr_accessible :number
      has_many :lesson_groups
    end
    

    A part of the documentation about the Options for has_one:

    :through

    Specifies a Join Model through which to perform the query. Options for :class_name, :primary_key, and :foreign_key are ignored, as the association uses the source reflection. You can only use a :through query through a has_one or belongs_to association on the join model.

    They talked about that here: Rails has_one :through association