简体   繁体   中英

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'

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) 

Use a scope method:

class Teacher < ActiveRecord::Base
  ...
  def self.connected
    includes(:user).where.not(users: { uid: nil }).references(:user)
  end
  ...

end

You'll use this like:

@teacher = Teacher.connected.order('created_at DESC')

假设您想要拥有用户的老师?

@teachers = Teacher.where.not(user_id: nil).order(created_at: :desc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM