基于关系搜索模型

时间:2014-10-22 13:19:38

标签: ruby-on-rails

我有一个属于旅行的主题模型。 Trip有一个start_date和end_date。 我想根据Trips日期找到主题。我如何在rails中设置此查询?

Topic.joins(:trip).where('trip.start_date > ?', Time.now)

这会引发以下错误。

  Topic Load (0.3ms)  SELECT "topics".* FROM "topics" INNER JOIN "trips" ON "trips"."id" = 
"topics"."trip_id" WHERE (trip.start_date < '2014-10-22 13:17:37.764743') ORDER BY created_at DESC
SQLite3::SQLException: no such column: trip.start_date: SELECT "topics".* FROM "topics" INNER JOIN     
"trips" ON "trips"."id" = "topics"."trip_id" WHERE (trip.start_date < '2014-10-22 13:17:37.764743')     
ORDER BY created_at DESC
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: trip.start_date: SELECT 
"topics".* FROM "topics" INNER JOIN "trips" ON "trips"."id" = "topics"."trip_id" WHERE 
(trip.start_date < '2014-10-22 13:17:37.764743')  ORDER BY created_at DESC

如何构建此查询错误?

1 个答案:

答案 0 :(得分:1)

Rails中的表名按惯例是复数(与型号名称相反),根据日志,此处就是这种情况。所以它应该是:

Topic.joins(:trip).where('trips.start_date > ?', Time.now)