【问题标题】:ActiveRecord - Display columns from multiple associationsActiveRecord - 显示来自多个关联的列
【发布时间】: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


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 请扩展您的答案以解释您在做什么以及为什么它将解决 OP 的问题。
    • 我试过了,这是我收到的错误:[50] pry(main)> user.user_profiles.select("profile_type.*, profile_type.connection_type").all PG::InFailedSqlTransaction:错误:当前事务被中止,在事务块结束之前忽略命令:SELECT profile_type.*, profile_type.connection_type FROM "user_profiles" WHERE "user_profiles"."user_id" = $1 => #>:0x8175818c>
    【解决方案2】:

    我能够弄清楚如何使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多