views:

91

answers:

3

I have following:

User model with columns:

id     user_id     password     created_at     updated_at

Store model with columns:

id     store_id    store_name   create_ad      updated_at

Basically a user can belong to multiple stores. So I would want to get a query like "get all the stores that the user belongs to"

Relationships I've made are:

class User < ActiveRecord::Base
    belongs_to :store, :foreign_key => "store_id"
end

class Store < ActiveRecord::Base
    has_many    :user, :foreign_key => "store_id"
end

are these correct?

Ultimately I want to find out whether a userid, password and storeid should be able to login.

So how can I use the find_byXXX on this ? so If I get a row back with passed in userid, password and storeId...I would know whether user should be able to login?

I noticed that belongs_to and has_many questions have been asked before but I was not able to understand well from those questions. maybe answers specific to my problem will help...

A: 

So you've said that a user belongs to many stores. How many users belong to a single store? If the answer is more than 1, then what you need is has_and_belongs_to_many and a third database table. The table will essentially contain pairs of (store_id, user_id).

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Although it is not required by Rails, it is recommended that you create a model for this relation and make the relation bidirectional on that model. You will thank yourself later.

class User < ActiveRecord::Base
    has_many :userstores
    has_many :stores, :through => :userstores
end

class Store < ActiveRecord::Base
    has_many :userstores
    has_many :users, :through => :userstores
end

class UserStore < ActiveRecord::Base
    belongs_to :user
    belongs_to :store
end
BennyG
@BennyG "and make the relation bidirectional on that model." Are you speaking of two `has_many :through` relations?
Tim Snowhite
The new model (UserStore) will have two `:has_one` relations. And yes, you can add `has_many :through` relations for convenience to both the User and Store model.
BennyG
A: 

You're looking for a has_and_belongs_to_many relationship. Your tables and model should be as follows:

User Table:

id password created_at updated_at

Store Table:

id store_name created_at updated_at

Join Table (called stores_users):

store_id user_id

In your models:

class User < ActiveRecord::Base
   has_and_belongs_to_many :stores
end

class Store < ActiveRecord::Base
    has_and_belongs_to_many :users
end

To get a user's stores:

User.stores

See the rails API for more information.

mjaz
User.stores does not return my anything it says Undefined method 'stores'
mustaine
Did you add the join table?
mjaz
A: 

It seems like you're making a lot of false assumptions about how ActiveRecords works on a basic level, so I would recommend reading the official and very straightforward ActiveRecord Associations guide.

Daniel Owens