Reputation: 101
I have two models already created and properly working:
class Track < ActiveRecord::Base
has_many :grand_prixes
end
class GrandPrix < ActiveRecord::Base
belongs_to :track
end
My database schema is:
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"
I am able to can find the GrandPrix that are associated with a Track by id, but I want to find the GrandPrix in the table by the id of the track previously searched by track's name (a variable that comes from another site):
GrandPrix.where (track_id: 2)
This works and returned the GP I want.
I want to search by name:
GrandPrix.where (Track.name = "thenameIwant")
and to return my id:
SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant';
Then it would be something like this:
GrandPrix.where (Track.id = SELECT id FROM WHERE tracks tracks.name LIKE 'thenameIwant')
Upvotes: 3
Views: 50
Reputation: 11235
Use the joins
keyword to join the two relations:
GrandPrix.joins(:track).where(tracks: {name: "thenameIwant"})
Note the plural "tracks" in the where clause since your table name is "tracks"
Upvotes: 1