1

I have three models; events, users and entries. I would like on my users page for to be able to retrieve information relating to the events associated with the event associated with the user.

def show
    @user = User.find(params[:id])
    @entry = @user.entries.paginate(page: params[:page])
  end

It is more than happy with @user.entries.count but I would like to link up in a table something like this:

Event Name - Event Location - Course

My models are bellow:

class Event < ApplicationRecord
    has_many :entries, dependent: :destroy

class User < ApplicationRecord
    has_many :entries, dependent: :destroy

class Entry < ApplicationRecord
    belongs_to :user
    belongs_to :event

1 Answer 1

1

If they're related as:

class User < ApplicationRecord
  has_many :events
end

class Event < ApplicationRecord
  has_many :entries
  belongs_to :user
end

class Entry < ApplicationRecord
  belongs_to :event
end

Then you can use joins starting from Entry, up to User and check events where the user id is the one what you need:

Entry.joins(event: :user).where(users: { id: user_id })
Sign up to request clarification or add additional context in comments.

9 Comments

I get this error on rails console. 'NameError: undefined local variable or method user_id for main:Object' ?
user_id is a placeholder value I added as example, you need to use a numeric value corresponding to any user id that you know exists in your database @Tom :).
I tried - entry = Entry.joins(event: :user).where(users: { id: 2 }) I still get nowhere. Apparently, 'ActiveRecord::ConfigurationError: Can't join 'Event' to association named 'user'; perhaps you misspelled it?' . What should 'user' refer to?
Okay, I'm looking at your models now.
For your models, does this work Entry.joins(:event, :user).where(users: { id: 1 })?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.