Ask A Question

Notifications

You’re not receiving notifications from this thread.

Need some help with an Active Record Query

Simon P asked in Rails
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.


Reply
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.
Reply
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


Reply
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

Check https://stackoverflow.com/a/11601221/3670272
Reply
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:

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!
Reply
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

Reply
Thank you!
Reply
Join the discussion
Create an account Log in

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

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

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