按关联表的列排序

时间:2012-12-12 09:40:05

标签: ruby-on-rails-3 postgresql associations

我正在尝试从关联的表中获取特定订单。这是我的设置:

我的旅行中添加了triplocations。 Triplocation表有一列,用于定义名为location_order的列的位置顺序。现在,当我在show方法中收集我的单程旅行时,我想订购此专栏。

我尝试了@trip = Trip.find(params[:id], :order=> 'triplocations.location_order'),但收到了以下错误:

PG::Error: ERROR:  missing FROM-clause entry for table "triplocations" LINE 1: ....* FROM "trips"  WHERE "trips"."id" = $1 ORDER BY triplocati...

如何订购我的location_order?

提前致谢!

2 个答案:

答案 0 :(得分:1)

听起来您希望对triplocations关联进行排序,即按位置顺序排序@trip.trip_locations

我建议将默认范围添加到TripLocation

default_scope :order => 'location_order DESC'

答案 1 :(得分:0)

首先,find只会给你一条记录,所以你想要在哪里使用或者找到所有记录。

其次,如果你想要返回TripLocations而不是旅行,你需要用那个

开始查询

试试这个:

TripLocations.where(:trip_id => params[:id]).order(:location_order)

如果您想在旅行中订购地点,您也可以通过模型中的关联进行订购

# load the trip
@trip = Trip.find(params[:id])

# order the locations
@locations = @trip.triplocations.order(:location_order)