gpt4 book ai didi

ruby-on-rails - Rails Association 如果 bool 值为真

转载 作者:数据小太阳 更新时间:2023-10-29 08:27:21 24 4
gpt4 key购买 nike

我有两个模型,一个用户模型和一个类(class)模型

用户模式如下所示:

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

类(class)架构如下所示:

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

我只想让 teacher/admin bool 值为 true 的用户拥有 taught_courses但据我所知,您不能将关联包装在 if 语句中,因为老师?/管理员?方法不可用,我该如何处理?

最佳答案

我认为你可以这样做:

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

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

关于ruby-on-rails - Rails Association 如果 bool 值为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22501966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com