hellomello
hellomello

Reputation: 8597

Rails :through associations getting error, couldn't find association

I have 3 models,

Users, Location, Items

Location would only have 1 user, but User has many items or locations. and Items belongs to user or location.

class Location < ActiveRecord::Base
  belongs_to :user
  has_many items, through: :users
end

class User < ActiveRecord::Base
  has_many :locations
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :user
end

But I'm getting this error:

Could not find the association :users in model Location

I know, I can add has_many :users in Location model, but location is supposed to only have 1 user.

Upvotes: 0

Views: 325

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34336

This should be it:

class Location < ActiveRecord::Base
  has_one :user
  has_many items, through: :user
end

class User < ActiveRecord::Base
  belongs_to :location
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :user
end

To make more sense, read it this way:

Location has_one user

User belongs_to location

User has_many items

Item belongs_to user

Location has_many items, through: :user

Essentially you are delegating a model relationship to another model. So instead of having to call location.user.items you can just do location.items.

Upvotes: 1

MilesStanfield
MilesStanfield

Reputation: 4649

because you say ...

I know, I can add has_many :users in Location model, but location is supposed to only have 1 user.

Instead of has_many :users you could do this

has_one :user

Upvotes: 1

Related Questions