Newbie question on has_many

I have two classes: a Widget and a User. The User has an id that is referenced in two places on the Widget: owner_id and operator_id.

How should I structure that reference for has_many?

Thanks folks - I appreciate any help on this.

--David

widget.rb

has_many :owners, :class_name => "user", :foreign_key => "owner_id" has_many :operators, :class_name => "user", :foreign_key => "operator_id"

then in the widget database you have those two fields 'owner_id" and "operator_id"

:slight_smile:

Just what I needed - thanks sw0rdfish. The books I have were not real clear on this.

--David

Hmmm - now that I look at it, should it be belongs to?

widget.rb

belongs_to: owners, :class_name => "user", :foreign_key => "owner_id" belongs_to: operators, :class_name => "user", :foreign_key => "operator_id"

?

Each widget has a single owner and operator. A user can be the owner and/or operator of many widgets.

--David

Hmmm - now that I look at it, should it be belongs to?

widget.rb

belongs_to: owners, :class_name => "user", :foreign_key => "owner_id" belongs_to: operators, :class_name => "user", :foreign_key => "operator_id"

it's belongs_to (and then the corresponding has_many on user). You
need to use singulars though and the class name should be the actual
class name, ie belongs_to :owner, :class_name => "User" (the foreign key is inferred
from the association name)

I wrote this up in detail: Creating multiple associations with the same table - Space Vatican

Fred

Yeah Fred got ya... I just based it on your title, and assumed ( shame on me :frowning: )

If a user has_many widgets then yeah m use belongs_to and owner, not owners.

Writeup looks good too... have a look at it.

Fred, great write up - thanks for taking the time to put that up!

--David