0

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.

hellomello
  • 8,219
  • 39
  • 151
  • 297

2 Answers2

1

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.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • But what if user has many locations? Can I have belongs_to and has_many locations? – hellomello Aug 24 '15 at 03:15
  • I think so, you can have both `belongs_to location` and `has_many locations` in the User model. Give it a shot and let me know! To do so, this might help and give you some idea: http://stackoverflow.com/questions/4516416/belongs-to-and-has-many-to-the-same-model – K M Rakibul Islam Aug 24 '15 at 03:23
  • I just go this error... `ERROR: column users.location_id does not exist LINE 1: SELECT "users".* FROM "users" WHERE "users"."location_id" = $1 ...` Does that mean, I need to add a `location_id` to user table? If so, I think this is wrong association then because, if user has multiple locations, then how would the `user` table store multiple `location_id`? Just trying to figure out how this association should work... I think I'm almost there – hellomello Aug 24 '15 at 03:31
  • Yes, thats correct. Add `location_id` to the `users` table. – K M Rakibul Islam Aug 24 '15 at 03:32
  • That means this allows for only 1 location that user can have right? How do make it so user can have multiple locations? Or am I thinking this wrong? – hellomello Aug 24 '15 at 03:40
  • if you want `user has_many locations` then you have to have: `location belongs_to user` – K M Rakibul Islam Aug 24 '15 at 03:44
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87731/discussion-between-k-m-rakibul-islam-and-hellomello). – K M Rakibul Islam Aug 24 '15 at 03:49
1

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
MilesStanfield
  • 4,571
  • 1
  • 21
  • 32