gpt4 book ai didi

mysql - 多态关联属性的 Rails 别名

转载 作者:行者123 更新时间:2023-11-28 23:25:12 25 4
gpt4 key购买 nike

我有一个 Rails 应用程序,其中有多种类型的用户使用多态关联,如下所示:

用户:

class User < ActiveRecord::Base
belongs_to :profile, :polymorphic => true
has_many :posts
end

玩家:

class Player < ActiveRecord::Base
has_one :user, as: :profile
end

教练:

class Coach < ActiveRecord::Base
has_one :user, as: :profile

结束

比方说,这些表的模式如下:

User(userId: integer, username: string, created_at: datetime, updated_at: datetime, profile_id: integer, profile_type: string)

Player(playerId: integer, playerName: string, created_at: datetime, updated_at: datetime)

Coach(coachId: integer, coachName: string, created_at: datetime, updated_at: datetime)

Post(postId: integer, userId: integer, content: string ...)

球员和教练可以撰写帖子,这些帖子将连同他们的用户 ID 添加到数据库中。这很简单,但现在我想要一个返回所有帖子的查询,以及撰写帖子的球员或教练的姓名。或者根据这些相同的名称字段查询用户,以便能够进行名称搜索并获取用户 ID。

由于名称列有不同的标题,我不能只做User.profile.name,我也不知道有什么合适的方法可以根据“子”表的内容查询用户.我不想每次都检查 profile_type 然后根据它寻找不同的东西。是否可以给这些字段起一个别名之类的?无论类型如何,我该怎么做才能获得他们的字段?

最佳答案

查看 alias_attribute .

class Player < ActiveRecord::Base
alias_attribute :name, :column_name
end

关于mysql - 多态关联属性的 Rails 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39669457/

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