Ask A Question


You’re not receiving notifications from this thread.

Need some help with an Active Record Query

Simon P asked in Rails

I have these tables:

Users which has many:
Farms which has many:

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: 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

Hey Simon, 

You should be able to use a through association here to get what you want.

has_many :farms
has_many :stores, through: :farms

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:})
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

Thank you!
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 84,256+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.