Reputation: 65
I have a rails application where there are multiple types of users using a polymorphic association, like this:
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. 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.
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. I don't want to have to check the profile_type each time and then look for a different thing depending on it. Is it possible to give these field an alias or something? What can I do to get their fields regardless of type?
Upvotes: 1
Views: 712
Reputation: 52357
Take a look into alias_attribute
.
class Player < ActiveRecord::Base
alias_attribute :name, :column_name
end
Upvotes: 2