Need some help with an Active Record Query
Hi
I have these tables:
Users which has many:
Farms which has many:
Stores
I want to return stores that belong to a specific user_id.
Got this far but Rails is giving me an error.
Thanks in advance for any assistance.
I have these tables:
Users which has many:
Farms which has many:
Stores
I want to return stores that belong to a specific user_id.
Got this far but Rails is giving me an error.
Thanks in advance for any assistance.
Can you post your error?
Typically an example AR query that does what you want would be:
Stores.where(user_id: current_user.id).first If you aren't using devise or a current_user method, you can simply pass in the `id` against `user_id` from a param or some other method. Hope this helps.
Typically an example AR query that does what you want would be:
Stores.where(user_id: current_user.id).first If you aren't using devise or a current_user method, you can simply pass in the `id` against `user_id` from a param or some other method. Hope this helps.
Reading this back I should probably explain some more detail.
Users have multiple farms
Farms have multiple stores
I need a query that returns all stores for any farm being to current_user
Users have multiple farms
Farms have multiple stores
I need a query that returns all stores for any farm being to current_user
Hey Simon,
You should be able to use a through association here to get what you want.
You should be able to use a through association here to get what you want.
has_many :farms has_many :stores, through: :farms
Check https://stackoverflow.com/a/11601221/3670272
Thanks for everyones help.
I have added the "through" action.
My code looks like:
@stores = Farm.joins(:stores).where(stores: {marketing_year: view_year}).where(farms: {user_id: current_user.id})
But I get error:
I have added the "through" action.
My code looks like:
@stores = Farm.joins(:stores).where(stores: {marketing_year: view_year}).where(farms: {user_id: current_user.id})
But I get error:
undefined method `farm_id' for #<Farm:0x007f8d8352e708> Did you mean? farm_name
So I guess the query isn't returning the data I am hoping for when it tried to bind in the view.
Apologies for beginner level questions!
Assuming you're using devise, to get all the stores that the current_user has access to, the query would be
@stores = current_user.stores