Forum: Ruby on Rails one association from two

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E644de443b063a7a0d78a04f02cfa8cd?d=identicon&s=25 dschruth (Guest)
on 2008-12-12 21:50
(Received via mailing list)
I'm working on a two-to-many relationship that works fine from the
child object's perspective but not from the parent's.    The
imperfect, yet functional code looks like this:
-------------------------------------------------------------------
class PrimaryTable < ActiveRecord::Base
  has_many :secondary_tables_1 ,
            :foreign_key => :A_primary_table_id,
           :class_name => "SecondaryTable"
 has_many :secondary_tables_2 ,
           :foreign_key => :B_primary_table_id,
           :class_name => "SecondaryTable"
end

class SecondaryTable < ActiveRecord::Base
  belongs_to :A_primary_table,
           :foreign_key => :A_primary_table_id,
           :class_name => "PrimaryTable"
  belongs_to :B_primary_table,
           :foreign_key=> :B_primary_table_id,
            :class_name => "PrimaryTable"
end
------------------------------------------------------------------------------------------

But, I don't want to have two linking fields up *and* two linking
fields down.  I only want one linking field down.  I would like to
lump these parent to child relationships into one associated link...
doing something like this:

------------------------------------------------------------------------------------------

class PrimaryTable < ActiveRecord::Base
  has_many :secondary_tables ,
           :foreign_key => :A_primary_table_id,
           :foreign_key => :B_primary_table_id,
           :class_name => "SecondaryTable"
end

-------------------------------------------------

...but only one of the two links (the ones to "B_primary_table") shows
up this way.


Does any body have any idea how to do this?  I would think this would
be an easy thing to do.

Dave
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2008-12-18 01:38
(Received via mailing list)
dschruth wrote:
>            :class_name => "SecondaryTable"
> 
------------------------------------------------------------------------------------------
>            :foreign_key => :A_primary_table_id,
>            :foreign_key => :B_primary_table_id,
>            :class_name => "SecondaryTable"
> end
>
> -------------------------------------------------
>
> ...but only one of the two links (the ones to "B_primary_table") shows
> up this way.

Using the :finder_sql option to has_many, you'll have to write
custom SQL that does an "or" on the two foreign keys.

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.