Search code examples
associationsruby-on-rails-3devise

how to display records that are only connected to a single user


I hope you can help me here.

I want the users only to be able to see the appointments to the courses they are assigned to. How do I set it up in the controllers?

I got 3 models:

class Appointment < ActiveRecord::Base  
  belongs_to :user
  belongs_to :course
end

class User < ActiveRecord::Base  
  has_many :courses, :through => :assignments
  has_many :appointments
end

class Course < ActiveRecord::Base
  has_many :users, :through => :assignments
  has_many :appointments
end

Solution

  • You should just be able to do:

    @appointments = current_user.appointments
    

    Or am I missing something in your question?


    Edit: A more detailed example:

    In your controller (let's say it's AppointmentsController):

    class AppointmentsController < ApplicationController
    
      def index
        @appointments = current_user.appointments
      end
    
    end
    

    Then, in the corresponding view (appointments/index.html.erb):

    <%- @appointments.each do |appointment| -%>
      <%= appointment.name %>
    <%- end -%>
    

    This is all based on the assumption you have current_user available, but since you've tagged the question with 'devise', I'm assuming you do.