【发布时间】:2014-06-27 19:35:16
【问题描述】:
我有一个用户、user_profile 和 profile_type 模型。一个用户有_many user_profiles,一个user_profile 属于一个用户,属于一个profile_type,一个profile_type 有_many user_profiles。
我一直在阅读有关如何完成这项工作的信息,但我在解决这个问题时遇到了问题,我们将不胜感激。
我知道我可以通过这样的语句使用 SQL 来做到这一点(手写 SQL,请原谅错误),但我想使用 ActiveRecord。
Select up.id, u.user_id, pt.connection_type
from user u
join user_profile up
on u.user_id = up.user_id
join profile_type pt
on pt.profile_type_id = up.profile_type_id
where u.username = "test"
我想为关联用户返回嵌套的 user_profile 对象,但我希望 user_profile 对象包含 profile_type.connection_type 而不是 profile_type.profile_id。
目前,如果我这样做,
user.user_profiles.all
添加然后遍历返回的嵌套 user_profiles,这是我的输出:
{
:id
:user_id
:profile_type_id
}
我想要的是:
{
:id
:user_id
:profile_type.connection_type (instead of profile_type.profile_type_id)
}
用户模型
class User < ActiveRecord::Base
has_many :user_profiles, autosave: true
has_many :account_settings, autosave: true
end
User_Profile 模型
class UserProfile < ActiveRecord::Base
belongs_to :user
belongs_to :profile_type
end
用户配置文件类型模型
class ProfileType < ActiveRecord::Base
has_many :user_profiles
end
【问题讨论】:
标签: ruby-on-rails-4 rails-activerecord