如果布尔值为true,则为Rails Association

时间:2014-03-19 09:52:01

标签: ruby-on-rails ruby if-statement associations conditional-statements

我有两个模型,一个用户模型和一个课程模型

用户架构如下所示:

create_table "users", force: true do |t|
    t.string   "username",                        default: "",    null: false
    t.string   "first_name",                      default: "",    null: false
    t.string   "last_name",                       default: "",    null: false
    t.string   "password_digest",                 default: "",    null: false
    t.string   "email",                           default: "",    null: false
    t.string   "email_unconfirmed",               default: "",    null: false
    t.string   "email_verification_token",        default: "",    null: false
    t.string   "password_reset_token",            default: "",    null: false
    t.datetime "password_reset_token_expires_at"
    t.boolean  "admin",                           default: false
    t.boolean  "teacher",                         default: false
    t.datetime "created_at"
    t.datetime "updated_at"
end

课程架构如下所示:

create_table "courses", force: true do |t|
    t.integer  "teacher_id"
    t.string   "name"
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
end

用户模型:

class User < ActiveRecord::Base
    has_many :taught_courses, :foreign_key => :teacher_id 
end

我只想让教师/管理员布尔为true的用户拥有taught_courses 但据我所知,你不能将关联包装在if语句中,导致老师?/ admin?方法不可用所以我该如何处理?

1 个答案:

答案 0 :(得分:6)

我认为你可以这样做:

class User < ActiveRecord::Base
    has_many :taught_courses, -> { where(admin: true, teacher: true)}, :foreign_key => :teacher_id 
end

您可以在线阅读有关ActiveRecord Conditional Associations的更多信息,并在此处查看示例:

4.1.3.1 where

The where method lets you specify the conditions that the associated object must meet.

class Order < ActiveRecord::Base
  belongs_to :customer, -> { where active: true }
end

<强>更新

如果您要使用其他模型进行验证,则可能需要使用.joins。但是,考虑到您正在ping原始模型,您可能希望使用ActiveRecord Association Extensions

这些允许您访问proxy_association对象,这使您能够通过内存访问“父”数据:

class User < ActiveRecord::Base
    has_many :taught_courses, :foreign_key => :teacher_id do
        def admins_and_teachers
            user = proxy_association.owner
            where("users.admin = ? AND users.teacher = ?", user.admin, user.teacher)
        end
    end
end

我认为这会奏效;如果没有,那肯定是我要看的路径