Search code examples
ruby-on-railshas-many-throughrelationships

has_many through with :class_name


I have the following:

belongs_to :type, :class_name => :activity_type
belongs_to :activity_type # needed for has_one :through?
has_one :category, :through => :activity_type, :class_name => :activity_category

Is there a way to do this "has_one through" relationship using "type" instead of "activity_type"?

Edit: This was not working, and I failed to see thanks to the magic word "type".

What I have now is this:

  belongs_to :company
  belongs_to :type, :class_name => 'ActivityType', :foreign_key => 'activity_type_id'
  has_one :category, :through => :type, :class_name => 'ActivityCategory', :foreign_key => 'activity_category_id'

But it fails with

  no such column: activity_types.category_id

which is correct, since the expected column would be "activity_types.activity_category_id". How can I fix that?


Solution

  • You're using associations in a wrong way. First of all when you use through: then class_name, foreign_key will be omitted. So this is why it's expecting category_id. Also I think that you shouldn't overload your associations with rewriting defaults options since when there's a lot of associations on a model it starts to look like a mess and hard to understand. So you probably should just write it as belongs_to :activity_type and add whatever name suits you best like alias_method :type, :activity_type.

    So in short, this is what I'm proposing you:

    belongs_to :company
    belongs_to :activity_type
    has_one :activity_category, :through => :activity_type
    
    alias_method :type, :activity_type
    alias_method :category, :activity_category