On Aug 8, 2012, at 2:11 PM, Quiliro Ordóñez wrote:

> I have constructed the following models:
> 
> 
> 
> class Work < ActiveRecord::Base
> 
>  hobo_model # Don't put anything above this
> 
>  fields do
>    name :string
>    url  :string
>    timestamps
>  end
> 
>  belongs_to :user
>  has_many :works, :through => :work_assignments, :accessible => true
>  has_many :work_assignments, :dependent => :destroy
> 
>  children :works
> 
> 
> 
> class WorkAssignment < ActiveRecord::Base
> 
>  hobo_model # Don't put anything above this
> 
>  fields do
>    timestamps
>  end
> 
>  belongs_to :work

Apologies for not replying sooner - I could have *sworn* that I had replied to 
an earlier post on this issue, but apparently there's a problem between my 
keyboard and chair. :)

Anyways, the issue is that you've only got a single foreign key field on 
WorkAssignment, which is confusing the associations. It's actually somewhat 
surprising that it doesn't give an error in this situation. You really want 
associations like this (skipping accessible options for now):

on Work:

has_many :work_assignments, :dependent => :destroy
has_many :related_works, :through => :work_assignments

on WorkAssignment:

belongs_to :work
belongs_to :related_work, :class_name => 'Work'

If you'd like to traverse the links in the other direction, you can also add 
(to Work):

has_many :reverse_work_assignments, :dependent => :destroy, :class_name => 
'WorkAssignment', :foreign_key => 'related_work_id'
has_many :reverse_related_works, :through => :reverse_work_assignments, :source 
=> :work

An example will help here:

A is related to B and C
D is related to B and C and E

B's reverse_related_works are A and D
E's reverse_related_works are just D

If your relations are truly symmetrical, things are a bit trickier; the 
standard way I've handled things like that in the past is to denormalize the 
data just a little and build *two* WorkAssignment records (one in each 
direction). This complicates updating links a bit, but greatly simplifies 
retrieving things that are related.

--Matt Jones

-- 
You received this message because you are subscribed to the Google Groups "Hobo 
Users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/hobousers?hl=en.

Reply via email to