:has_many :through problems

Hi,

I’m fairly new to RoR and I’m having some problems with :has_many and
:through and it’s quite possible that I’m doing something very wrong…

The model - consists of items and the their dependencies. Items can
depend on each other; this is coded through the table ‘deps’ with keys
sub_item_id and super_item_id that refers to the items.id.

E.g.

deps
id,super_item_id,sub_item_id
1 , 1, 2
2 , 1, 3
3 , 2, 3

This means that item 1 has two sub items (namely 2 & 3), item 3 has two
super items (namely 1 & 2).

I use the following model:

class Item < AR::B
has_many :deps
has_many :sub_items, :through => :deps
has_many :super_items, :through => :deps
end

class Dep < AR::B
belongs_to :sub_item, :class_name => ‘Item’, :foreign_key =>
‘sub_item_id’
belongs_to :super_item, :class_name => ‘Item’, :foreign_key =>
‘super_item_id’
end

Whenever I try to access the sub or super items I get an sql error (e.g.
for item 1):

'Unknown column ‘deps.item_id’ in ‘where clause’: SELECT items.* FROM
items INNER JOIN deps ON items.id = deps.sub_item_id WHERE
((deps.item_id = 1))

It would seem that the last ((…)) should have been
((deps.super_item_id = 1)). But I’m not quite sure of how I would have
told the reflection of that key name (super_item_id).

I’ve tried any different variations of this without any luck.

Any clues or hints?

Regards,

  • Jacob

I figured out how to do it:

class Item < AR::B
has_many :sub_deps,
:class_name => ‘Dep’,
:foreign_key_name => ‘super_item_id’,
:source => deps

has_many :super_deps,
:class_name => ‘Dep’,
:foreign_key_name => ‘sub_item_id’,
:source => deps

has_many :sub_items, :through => :deps
has_many :super_items, :through => :deps
end

class Dep < AR::B
belongs_to :sub_item, :class_name => ‘Item’, :foreign_key =>
‘sub_item_id’
belongs_to :super_item, :class_name => ‘Item’, :foreign_key =>
‘super_item_id’
End

If anyone has a more elegant solution let me know. In particular it
would be nice not having to specify :class_name => ‘Dep’ when using
:source. It was also unintuitive to me that I needed two has_many
aliases for :deps but at least now I see why.

Regards,

  • Jacob

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs