gpt4 book ai didi

sql - ActiveRecord 的查找方法?帮助加入模型

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:24 26 4
gpt4 key购买 nike

我已经创建了两个模型并且可以正常工作:

class Track < ActiveRecord::Base
has_many :grand_prixes
end

class GrandPrix < ActiveRecord::Base
belongs_to :track
end

我的数据库架构是:

create_table "tracks", force: :cascade do |t|
t.string "track_name"
t.string "description"
t.string "country"
t.string "lenght"
t.integer "pit_boxes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ac_track_name"
end
add_index "tracks", ["ac_track_name"], name: "index_tracks_on_ac_track_name"




create_table "grand_prixes", force: :cascade do |t|
t.datetime "gp_date"
t.integer "max_slots"
t.integer "event_id"
t.integer "track_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end


add_index "grand_prixes", ["track_id"], name: "index_grand_prixes_on_track_id"

我能够通过 id 找到与轨道关联的大奖赛,但我想通过之前通过轨道名称(来自另一个站点的变量)搜索的轨道 id 在表中找到大奖赛:

GrandPrix.where (track_id: 2)

这有效并返回了我想要的 GP。

我想按名字搜索:

GrandPrix.where (Track.name = "thenameIwant") 

并返回我的 id:

SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant';

那么它会是这样的:

GrandPrix.where (Track.id = SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant')

最佳答案

使用joins关键字连接两个关系:

GrandPrix.joins(:track).where(tracks: {name: "thenameIwant"})

请注意 where 子句中的复数“tracks”,因为您的表名称是“tracks”

关于sql - ActiveRecord 的查找方法?帮助加入模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com