【问题标题】:Rails Joins query not responding like SQL Join queryRails Joins 查询没有像 SQL Join 查询那样响应
【发布时间】:2015-03-22 03:58:25
【问题描述】:

我有两个表,package 和 time_slot,我想加入并返回一些值

在我的 package.rb 中

class Package < ActiveRecord::Base
    attr_accessible :company_id, :time_slot_id, :location_id, :service_id, :day_id, :resource_quantity, :package_category_id, :time_slot, :is_booked
    belongs_to :time_slot
end

在我的 time_slot.rb 中

class TimeSlot < ActiveRecord::Base
    attr_accessible :start_time, :end_time
    has_many :package
end

在我的 sql 查询中,当我运行此查询时,它运行良好

SELECT packages.id, time_slots.start_time, time_slots.end_time FROM packages INNER JOIN time_slots ON packages.time_slot_id = time_slots.id;

这是结果

但是当我在 Rails c 中运行相同的查询时

Package.joins("LEFT JOIN time_slots ON packages.time_slot_id = time_slots.id").select("packages.id, time_slots.start_time, time_slots.end_time")

它只返回这个

 #<ActiveRecord::Relation [#<Package id: 1>, #<Package id: 2>, #<Package id: 3>]>

有人知道为什么吗?任何帮助表示赞赏

【问题讨论】:

  • 不知道这个问题。只是一个旁注 - 如果您需要像在 sql 查询中那样进行 INNER JOIN,只需使用 - joins(:time_slots)

标签: mysql sql ruby ruby-on-rails-4 join


【解决方案1】:

它不会“返回”那个。这就是它所返回的to_s 表示。

Package 模型没有 start_time 或 end_time 属性,因此控制台在检查关系时不会显示选定的值。

但每个对象在调用时返回这些值。再次运行查询并尝试添加:

.first.start_time

或者

.map(&:attributes)

【讨论】:

  • 是的,我阅读了一些文档并意识到这一天。完全浪费了我 2 小时试图找出错误所在。谢谢@pavling
  • 阅读文档绝不是浪费:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2017-07-12
  • 1970-01-01
  • 2018-02-22
  • 2016-10-24
  • 1970-01-01
  • 2014-08-12
相关资源
最近更新 更多