Usng Rails ActiveRecord relationships

Posted by Brian Goff on Stack Overflow See other posts from Stack Overflow or by Brian Goff
Published on 2010-12-31T22:53:39Z Indexed on 2011/01/01 1:54 UTC
Read the original article Hit count: 515

Filed under:

I'm a newbie programmer, been doing shell scripting for years but have recently taken on OOP programming using Ruby and am creating a Rails application.

I'm having a hard time getting my head wrapped around how to use my defined model relationships.

I've tried searching Google, but all I can come up with are basically cheat sheets for what has_many, belongs_to, etc all mean. This stuff is easy to define & understand, especially since I've done a lot of work directly with SQL.

What I don't understand is how to actually used those defined relationships.

In my case I have 3 models: Locations Hosts Services

Relationships (not actual code, just for shortening it):

Services
    belongs_to :hosts

Hosts
    has_many :services
    belongs_to :locations

Locations
    has_many :hosts

In this case I want to be able to display a column from Locations while working with Services. In SQL this is a simple join, but I want to do it the Rails/Ruby way, and also not use SQL in my code or redefine my joins.

© Stack Overflow or respective owner

Related posts about ruby-on-rails3