1

i need help with the following topic:

I'm trying to create an array of users based on their ids

  def show
    @appointment = Appointment.where(:event_id => :id).all
    @users = Array.new
    @appointment.each do |appointment|
      @users.fill(User.find(appointment.user_id))
    end

  end

First, im getting all appointments which event_id are the same to :id (which comes from the Event table) . Then i proceed to create an array to be filled later with users inside the .each do expression.

The problem is that @users is empty after the expresion ends.

What am i doing wrong?

2 Answers 2

2

Much simpler:

@users = User.find(Appointment.where(event_id: <id>).pluck(:id))

Your code does not work as you misunderstood what method fill does - it substitutes all elements of the array with passed object (pretty much like this, might take some extra params to alter its behaviour a little bit). You were most liekly looking for push or unshift methods.

Much better solution

If I am correct, your associations most likely looks like this:

Event has_many :appointments
Appointment belongs_to :user

n that case, you can simply create has_many :through association:

class Event < ActiveRecord::Base
  has_many :appointments
  has_many :users, through: :appointments
end

Then your query is just:

Event.find(<id>).users
Sign up to request clarification or add additional context in comments.

Comments

0
@users = Appointment.includes(:user).where(:event_id => <id>).map(&:user) 

should work, assuming you have the User has_many :appointments & Appointments belongs_to :user associations setup.

Comments

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.