【问题标题】:How to make a join between 2 tables in Rails that returns the data of both tables如何在 Rails 中的 2 个表之间建立连接,返回两个表的数据
【发布时间】:2011-12-27 09:23:45
【问题描述】:

我正在尝试加入两个表:RoomsRoom_Types(它们已经建立了关系)。问题是,我正在尝试做类似的事情:

room = Room.all :conditions => ['rooms.id = ?', @room_id],
                :joins      => :room_type

room.to_json

..这个 JSON 正在发送到我的视图。

但是,JSON 仅显示 Room 表的字段,不包括 Room_Type 字段,我需要此 JSON 中两个表的字段。我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby database join helper


    【解决方案1】:

    :joins 只执行JOIN。与 SQL 一样,这不会将 JOINed 表的列添加到结果中。如果你想这样做,你应该改用:include

    rooms = Room.all :conditions => [ 'rooms.id = ?', @room_id ],
                     :include    => :room_type
    rooms.to_json
    

    或者,用 Rails 3 的说法:

    rooms = Room.where(:id => @room_id).include(:room_type).all
    rooms.to_json
    

    【讨论】:

    • 您可能还需要在to_json 选项中使用:include
    • 如何在我的 to_json 中使用 :include ?
    • @content01 你检查过the documentation吗?
    【解决方案2】:

    试试

    Room.joins(:room_type).where(:id => @room_id).select('room_types.foo as foo, room_types.bar as bar')
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多