我有三个模型Hotel
,Package
,PackagePrice
,关联就像:
酒店可以有很多套餐,每个套餐都有一个packageprice
模型是:
class Hotel < ActiveRecord::Base
attr_accessor :excel_sheet, :excel_sheet_file_name
attr_accessible :hotel_name, :stars, :location, :searchable, :excel_sheet, :excel_sheet_file_name
has_many :package_prices, :dependent => :destroy
has_many :packages, :through => :package_prices, :order => 'package_prices.price'
end
class Package < ActiveRecord::Base
attr_accessible :package_name
has_many :package_prices, :dependent => :destroy, :order => 'price DESC'
has_many :hotels, :through => :package_prices, :order => 'package.package_prices.price'
end
class PackagePrice < ActiveRecord::Base
attr_accessible :price, :package_id, :hotel_id
belongs_to :package
belongs_to :hotel
end
和相应的表格是:
mysql> desc hotels
-> ;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| hotel_name | varchar(255) | YES | | NULL | |
| stars | varchar(255) | YES | | NULL | |
| location | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
| searchable | tinyint(1) | YES | | 1 | |
+------------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
mysql> desc packages;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| package_name | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> desc package_prices;
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| package_id | int(11) | YES | | NULL | |
| price | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
| hotel_id | int(11) | YES | | NULL | |
+------------+----------+------+-----+---------+----------------+
我在变量@hotels
中有酒店记录,我希望按@hotels
顺序按price
过滤此asc or desc
。所以请帮我查一下这个问题。
答案 0 :(得分:2)
你会这样做,
@hotels = Hotel.joins(:package_prices).order('package_prices.price')
但是我不认为你的模型是按照你描述的方式设置的,所以我不确定这是否能达到你想要的效果