我已经创建了两个模型并正常工作:
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找到与Track相关联的GrandPrix,但我希望通过以前按轨道名称搜索的轨道的id(来自其他站点的变量)找到表格中的GrandPrix :
GrandPrix.where (track_id: 2)
这有效并返回了我想要的GP。
我想按名称搜索:
GrandPrix.where (Track.name = "thenameIwant")
并返回我的身份:
SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant';
那就是这样的:
GrandPrix.where (Track.id = SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant')
答案 0 :(得分:1)
使用joins
关键字加入两个关系:
GrandPrix.joins(:track).where(tracks: {name: "thenameIwant"})
注意复数&#34;曲目&#34;在where子句中,因为你的表名是&#34; track&#34;