Rails - 检查父模型属性是否存在
Rails - Check if Parent model attribute is present
我想显示已将其帐户连接到我们的付款购买者提供商的教师列表。当教师连接他们的支付账户时,它会更新用户模型上的支付 uid 字段。
我们的模型是这样设置的:
class User < ActiveRecord::Base
has_one :teacher
class Teacher
belongs_to :user
我的教师控制器:
class TeachersController < ApplicationController
def index
@teachers = Teacher.order('created_at DESC')
end
我想显示这样的东西:
@teachers = Teacher.where(self.user.uid.present?).order('created_at DESC')
但是我收到了 TeachersController'
的 NoMethodError 'undefined method `user'
使用范围方法:
class Teacher < ActiveRecord::Base
...
def self.connected
includes(:user).where.not(users: { uid: nil }).references(:user)
end
...
end
您将像这样使用它:
@teacher = Teacher.connected.order('created_at DESC')
假设您需要有用户的教师?
@teachers = Teacher.where.not(user_id: nil).order(created_at: :desc)
尝试:
@teachers = Teacher.joins(:user).where.not('users.uid = ?',nil).order(created_at: :desc)
或
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)
我想显示已将其帐户连接到我们的付款购买者提供商的教师列表。当教师连接他们的支付账户时,它会更新用户模型上的支付 uid 字段。
我们的模型是这样设置的:
class User < ActiveRecord::Base
has_one :teacher
class Teacher
belongs_to :user
我的教师控制器:
class TeachersController < ApplicationController
def index
@teachers = Teacher.order('created_at DESC')
end
我想显示这样的东西:
@teachers = Teacher.where(self.user.uid.present?).order('created_at DESC')
但是我收到了 TeachersController'
的 NoMethodError 'undefined method `user'使用范围方法:
class Teacher < ActiveRecord::Base
...
def self.connected
includes(:user).where.not(users: { uid: nil }).references(:user)
end
...
end
您将像这样使用它:
@teacher = Teacher.connected.order('created_at DESC')
假设您需要有用户的教师?
@teachers = Teacher.where.not(user_id: nil).order(created_at: :desc)
尝试:
@teachers = Teacher.joins(:user).where.not('users.uid = ?',nil).order(created_at: :desc)
或
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)