On Sat, Mar 5, 2011 at 4:13 PM, Alexey M. <[email protected]> wrote:

> Hello, I am re-opening this again, sorry :).
>
> I have just read in RailsGuides (
> http://guides.rubyonrails.org/association_basics.html )
> about the proper way to choose between belongs_to and has_one.
> From this point of view, something like belongs_to_many seems to be
> really missing, but i do not know if maybe there is a better name, and
> how to call the other side of the association (has_a ?).
> I am talking about something like this:
>
> class Member < ActiveRecord::Base
>  has_an :address
> end
>
> class Address < ActiveRecord::Base
>  belongs_to_many :members
> end
>
> Different members can have the same address, if they are a couple for
> example.
>
> This can me implemented the same way as has_and_belongs_to_many, except
> that in the joint table the Foreign Key for Members must be required to
> be unique.
>
> An Address can be then automatically deleted when the last Member living
> at that address is deleted.
>
> The advantage over [belongs_to, has_many] is the same as for has_one
> over belongs_to: the Members table does not need to "know" about the
> Addresses table.
>

The thing is, this would just duplicate existing associations; I don't see
how it's needed. The relationship you describe above can be written much
simpler (no join table at all) by just having User belongs_to :address, and
Address has_many :users.

If it's the readability of the code that you want, you can always do things
like

class Address << ActiveRecord::Base

  has_many :residents, :class_name => "User"

end

class User << ActiveRecord::Base

  belongs_to :address, :foreign_key => "resident_id"

end

For many-to-many, I really tend to favor has_many :through associations from
both sides, as they're more flexible.

But honestly; I don't think belongs_to_many is missing. Just my 2ยข. :-)


> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" 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/rubyonrails-talk?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" 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/rubyonrails-talk?hl=en.

Reply via email to