Has_one vs. Belongs_to?


#1

I have clients, (table - model-controller) and I have plans (table -
model - controller). A client can have several plans and a plan can
only map to one client. I would assume that in the model for clients
i need a has_many and in the model for plans I need either a has_one
or a belongs_to. I am not sure which to use and obviousely it is not
entirely clear to me (after reading in agile web developement) what
these methods are doing for me, other than it seems to be obviouse i
should have these relationships in place.


#2

belongs_to would look like this:

clients (table)
id
name
etc

plans (table)
id
client_id
name

client.rb (model)
has_many :plans

plan.rb (model)
belongs_to :client

has_one is just like has_many, but it restricts the selection.

clients (table)
id
name
plan_id
etc

plans (table)
id
name

client.rb (model)
belongs_to :plan

plan.rb (model)
has_one :client

The first example is probably what you want (one to many) and the
second
example is probably not what you want (one-to-one).

belongs_to is used on the model that contains the foreign key. If the
plans table has the client_id foreign key, the plan belongs_to :client
and
the client has_many :plans. (see how that makes sense when you say it
out
loud?) It doesn’t make as much sense to say that a client belongs_to
a
plan though.

Hopefully I helped clear it up a bit instead of confusing you more.


#3

removed_email_address@domain.invalid wrote:

I have clients, (table - model-controller) and I have plans (table -
model - controller). A client can have several plans and a plan can
only map to one client. I would assume that in the model for clients
i need a has_many and in the model for plans I need either a has_one
or a belongs_to. I am not sure which to use and obviousely it is not
entirely clear to me (after reading in agile web developement) what
these methods are doing for me, other than it seems to be obviouse i
should have these relationships in place.

belongs_to always goes in the model that has the foreign key in its
table. Client would have a plan_id field, so it belongs_to :plan.

This is what I wrote as “required reading” for associations and basic
relationships.

http://blog.hasmanythrough.com/2007/1/15/basic-rails-association-cardinality


Josh S.
http://blog.hasmanythrough.com


#4

thank you both, super helpful
JE

On Apr 18, 2:07 pm, Josh S. removed_email_address@domain.invalid