Search code examples
ruby-on-railsrubyruby-on-rails-4associationsnested-attributes

Rails - Check if Parent model attribute is present


I want to display a list of teachers who have had their accounts connected to our payment purchaser provider. When a teacher connects their payment account it updates a payment uid field on the User model.

Our models are set up like this:

class User < ActiveRecord::Base
    has_one :teacher

class Teacher
    belongs_to :user

My Teachers Controller:

class TeachersController < ApplicationController
    def index
        @teachers = Teacher.order('created_at DESC')
    end

I want to display something like this:

@teachers = Teacher.where(self.user.uid.present?).order('created_at DESC')

But I am returned a NoMethodError 'undefined method `user' for TeachersController'


Solution

  • Try:

    @teachers = Teacher.joins(:user).where.not('users.uid = ?',nil).order(created_at: :desc)
    

    OR

    valid_users = User.where.not(uid: nil).pluck(:id) # return array of all user's id which has not uid nil
    @teachers = Teacher.where(user_id: valid_users).order(created_at: :desc)