Mysql 使用:include语句查找记录
我正在使用RubyonRails2.3.2,并且正在学习如何使用:include语句Mysql 使用:include语句查找记录,mysql,ruby-on-rails,Mysql,Ruby On Rails,我正在使用RubyonRails2.3.2,并且正在学习如何使用:include语句 Announcement.find_by_sql 'select * from announcements ann inner join rates r on ann.id = r.announcement_id order by r.average DESC' 我想把所有的公告都按价格排序。我有两个模型和表格:公告和价格 模型如下所示: class Announcement < ActiveRec
Announcement.find_by_sql 'select * from announcements ann inner join rates r on ann.id = r.announcement_id order by r.average DESC'
我想把所有的公告都按价格排序。我有两个模型和表格:公告和价格
模型如下所示:
class Announcement <
ActiveRecord::Base
belongs_to :rate
end
class Rate < ActiveRecord::Base
belongs_to :announcement
end
我已经试过了:
Announcement.paginate :page => params[:page], :per_page => 10, :include => [:rates], :order => 'rates.average DESC'
但是它试图将rates.id=announcements.id关联起来,而不是rates.announcement\u id=announcement\u id
我如何才能指定正确的关系来实现这一目标?正如Yuri在评论中指出的那样,您错误地定义了您的关系 公告应该有一个:费率 作为announcment上的命名范围:
class Announcement < ActiveRecord::Base
has_one :rate
named_scope :order_by_rate, :include => :rate, :order => 'rates.average DESC'
end
Announcement.order_by_rate.paginate :per_page => 10, :page => params[:page]
不含include@a。在需要时才填充费率
@a = Association.first
@a.rate #=> @a.rate is populated here, with a separate SQL statement.
您在公告模型中有错误的关系。如果一个annoulmet有多个费率,请尝试使用Announcement has_one:rate或has_mu many:rates,而不是belown to:rate谢谢。如果我想按多个字段订购呢?如果我添加另一个名为“范围”:order\u by\u featured。。。。。。然后将其用作公告。order_by_rate_和order_by_featured?我相信这是一个SQL的东西,会优先考虑要排序的第一个参数。我在互联网上发现,要连接许多命名范围,必须使用点。例如:Announcement.order_by_featured.order_by_rate.paginate。
@a = Association.first
@a.rate #=> @a.rate is populated here, with a separate SQL statement.