需要Rails中的SQL查询帮助

时间:2010-11-13 12:55:12

标签: sql ruby-on-rails

在我的网站上,我正在尝试使用最新发布的图片显示远足径(滚动到“图片部分:http://www.trailheadfinder.com/trail_search/latest_trails)。但是,我使用的当前查询是按顺序显示路径发布的“第一张”图片。所以当以后添加新图片时,跟踪不显示在顶部。我有一个跟踪表和一个链接的trailpicture表。这是我使用的当前查询:

@trails_pictures = Trailpicture.find(:all,
                                     :limit => 20,
                                     :include => [:trail],
                                     :select => 'trailpictures.trail_id, trails.name, trails.short_description, trails.city, trails.state, trails.country',
                                     :group => 'trailpictures.trail_id',
                                     :conditions => ["trailpictures.parent_id is NULL"],
                                     :order => 'trailpictures.id DESC')

非常感谢任何帮助!

谢谢,

尼克,

2 个答案:

答案 0 :(得分:0)

您需要按created_at订购。 :)

答案 1 :(得分:0)

我终于明白了。这就是它需要写的方式:

@trails_pictures = Trail.find(:all,
                              :joins => 'INNER JOIN trailpictures ON trails.id = trailpictures.trail_id',
                              :limit => 20,
                              :conditions => ["trailpictures.parent_id is NULL"],
                              :select => 'trails.id, trails.name, trails.short_description, trails.city, trails.state, trails.country, max(trailpictures.id)',
                              :group => 'trails.id',
                              :order => 'max(trailpictures.id) DESC')