Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 ActiveRecord-显示来自多个关联的列_Ruby On Rails 4_Rails Activerecord - Fatal编程技术网

Ruby on rails 4 ActiveRecord-显示来自多个关联的列

Ruby on rails 4 ActiveRecord-显示来自多个关联的列,ruby-on-rails-4,rails-activerecord,Ruby On Rails 4,Rails Activerecord,我有一个用户、用户配置文件和配置文件类型模型。一个用户有多个用户配置文件,一个用户配置文件属于一个用户和一个配置文件类型,一个配置文件类型有多个用户配置文件 我一直在阅读关于如何得到这项工作,但我有问题,弄明白这一点,任何帮助将不胜感激 我知道我可以用像这样的写意SQL语句来实现SQL,请原谅我的错误,但我想使用ActiveRecord Select up.id, u.user_id, pt.connection_type from user u join user_profile up on

我有一个用户、用户配置文件和配置文件类型模型。一个用户有多个用户配置文件,一个用户配置文件属于一个用户和一个配置文件类型,一个配置文件类型有多个用户配置文件

我一直在阅读关于如何得到这项工作,但我有问题,弄明白这一点,任何帮助将不胜感激

我知道我可以用像这样的写意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\u profile对象,但我希望user\u profile对象包含profile\u type.connection\u类型,而不是profile\u type.profile\u id

现在,如果我这样做

user.user_profiles.all
添加然后遍历返回的嵌套用户配置文件,这是我的输出:

{
: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
用户配置文件模型

class UserProfile < ActiveRecord::Base
    belongs_to  :user
    belongs_to  :profile_type
end
用户配置文件类型模型

class ProfileType < ActiveRecord::Base
    has_many :user_profiles
end
试试这个:

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

我能想出如何用葡萄做这件事

因为已经创建了关联,所以我可以使用Grape实体公开我需要的关联。它可以无缝工作,我希望这能帮助其他有类似问题的人

为了得到我想要的,我需要收集所有的用户配置文件

userprofiles = user.user_profiles.all
然后,我用葡萄做了这个

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

请扩展您的答案,解释您正在做什么以及为什么它会解决OP的问题。我尝试过,这是我收到的错误:[50]prymain>user.user\u profiles。选择profile\u type.*,profile\u type.connection\u type.all PG::InFailedSqlTransaction:错误:当前事务被中止,在事务块结束之前忽略的命令:从user_profiles.user_id=$1=>