簡體   English   中英

多態關聯屬性的 Rails 別名

[英]Rails alias for attributes on polymorphic association

我有一個 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM