ActiveRecord - 显示多个关联的列

时间:2014-06-27 19:35:16

标签: ruby-on-rails-4 rails-activerecord

我有一个user,user_profile和profile_type模型。用户has_many user_profiles,user_profile belongs_to用户,belongs_to为profile_type,profile_type为has_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

2 个答案:

答案 0 :(得分:0)

试试这个:

user.account_settings.select("profile_type.*, profile_type.connection_type").all

答案 1 :(得分:0)

我能够弄清楚如何使用Grape来做到这一点。

由于已经创建了关联,我可以使用Grape实体从关联中公开我需要的内容。它无缝地工作,我希望这可以帮助其他遇到类似问题的人。

为了得到我想要的东西,我需要收集所有user_profiles

userprofiles = user.user_profiles.all

然后,我用Grape

介绍了这个
present :user_profile_settings, userprofiles, with: API::V1::Entities::UserProfile

而且,这是我的实体的样子:

  class UserProfile < Grape::Entity
    expose :profile_type, using: ProfileTypeEntity
  end

  class ProfileTypeEntity < Grape::Entity
    expose :connection_type
  end