简体   繁体   English

多态关联属性的 Rails 别名

[英]Rails alias for attributes on polymorphic association

I have a rails application where there are multiple types of users using a polymorphic association, like this:我有一个 rails 应用程序,其中有多种类型的用户使用多态关联,如下所示:

User:用户:

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

Player:球员:

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

Coach:教练:

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

end结尾

The schemas for these tables, let's say,are as follows:这些表的模式,比方说,如下:

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 ...)

Player and Coaches can write posts, which will be added to the Database with their userId.球员和教练可以写帖子,这些帖子将通过他们的用户 ID 添加到数据库中。 This is easy enough, but now I want a query that returns all posts, together with the name of the Player or Coach who wrote it.这很容易,但现在我想要一个查询,返回所有帖子,以及撰写帖子的球员或教练的姓名。 Or query Users based on these same name fields, to be able to do a name search and get userId.或者根据这些相同的名称字段查询用户,以便能够进行名称搜索并获取用户 ID。

Since the name columns have different titles, I can't just do User.profile.name , nor do I know any decent way to query Users based on the content of its "child" tables.由于名称列有不同的标题,我不能只做User.profile.name ,我也不知道根据其“子”表的内容查询用户的任何体面方法。 I don't want to have to check the profile_type each time and then look for a different thing depending on it.我不想每次都检查 profile_type 然后根据它寻找不同的东西。 Is it possible to give these field an alias or something?是否可以给这些字段一个别名或什么? What can I do to get their fields regardless of type?无论类型如何,我该怎么做才能获得他们的字段?

Take a look into alias_attribute .看看alias_attribute

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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