【问题标题】:Rails Join not showing fields from related table [duplicate]Rails Join不显示相关表中的字段[重复]
【发布时间】:2019-03-23 17:05:44
【问题描述】:

Profile.joins(:course) 不显示 :course 字段。

我试过了

Profile.joins(:course).select('profiles.*,courses.*')

它出现在 select 中,而不是 from 命令中,因此没有任何课程列出现。

配置文件加载(2.6 毫秒)从“配置文件”中选择课程。*,配置文件。* INNER JOIN "courses" ON "courses"."coursable_id" = "profiles"."id" AND "课程"."coursable_type" = $1 限制 $2 [["coursable_type", "个人资料"], ["限制", 11]]

@profile = Profile.joins(:course).select('profiles.*,courses.*')
@profile.department # a field on Courses table

NoMethodError(Profile::ActiveRecord_Relation:0x00007fb4f4955dc0> 的未定义方法“部门”)

解决方案:

@profile.first.department # a field on Courses table

【问题讨论】:

  • 添加一个代码示例,展示您如何尝试获得您所期望的。

标签: ruby-on-rails ruby ruby-on-rails-5.2


【解决方案1】:

Select 仅显示存在于您调用 select 的模型(即配置文件)上的列。但Course 的属性仍然可用。

即您可以像往常一样调用它们:

@profile = Profile.joins(:course).select('profiles.*,courses.*')
@profile.course_name # if course_name is a field of course

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多