I have two related models, Trip and Ride. A Trip may have a going ride or a returning ride. My ActiveRecord models look like this:
class Route < ActiveRecord::Base
has_one :trip
end
class Trip < ActiveRecord::Base
belongs_to :going_route, class_name: "Route"
belongs_to :returning_route, class_name: "Route"
end
However this throws me an issue when I want to access a trip from a route:
Route.first.trip
This throws a PostgreSQL error:
PG::UndefinedColumn: ERROR: column trips.route_id does not exist
How can I tell to the Route
class that his trip is under either going_route_id
or returning_route_id
? Or maybe there is another way around?
P.S: I've been looking for similar questions, there are a lot, but none is exactly like this one and solves my problem. If you have any tip on how to make the difference clearer, especially for the title. Here is some similar question
EDIT:
I've also tried using a lambda, as in matthew's duplicate proposition:
class FavoriteRoute < ActiveRecord::Base
has_one :favorite_trip, -> (route) { where("going_route_id = :id OR returning_route_id = :id", id: route.id) }
end
This will throw the same error. And if I assume I should use find_by
instead of where
since I need only one result, I have another error which I really don't understand:
NoMethodError: undefined method `except' for #<Trip:0x00007f827b9d13e0>