Forum: Ruby on Rails Multiple Relations between 2 tables

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.
Ray M. (Guest)
on 2006-05-30 03:14
So I am trying to figure out how I would go about creating the
relationships between two tables, but there are multiple relationships
happening.

The one I am trying to figure out is a one_to_one relationship + a
one_to_many relationship.

Example:
I have a home model and a location model
home has_one location
location has_many homes

The trouble is I have to be able to access both home.location and
location.homes
I don't want to have locations duplicate if multiple homes have the same
location.

Any help on this would be great!

-Ray
Bryan D. (Guest)
on 2006-05-30 03:23
Ray M. wrote:
> So I am trying to figure out how I would go about creating the
> relationships between two tables, but there are multiple relationships
> happening.
>
> The one I am trying to figure out is a one_to_one relationship + a
> one_to_many relationship.
>
> Example:
> I have a home model and a location model
> home has_one location
> location has_many homes
>
> The trouble is I have to be able to access both home.location and
> location.homes
> I don't want to have locations duplicate if multiple homes have the same
> location.
>
> Any help on this would be great!
>
> -Ray

class Home
  belongs_to :location
end

class Location
  has_many :homes
end

Now @home.location and @location.homes are available. has_one doesn't do
exactly what you're hoping it would. Use belongs_to.
This topic is locked and can not be replied to.