在Rails 4中将SQL查询转换为活动记录

在Rails 4中将SQL查询转换为活动记录,sql,activerecord,ruby-on-rails-4,Sql,Activerecord,Ruby On Rails 4,这是我的两个模型 class Comment < ActiveRecord::Base belongs_to :phone end class Phone < ActiveRecord::Base has_many :comments, :dependent => :destroy end 下面是运行的原始SQL SELECT phones.ccount , comments.* FROM phones INNER JOIN comments ON

这是我的两个模型

class Comment < ActiveRecord::Base
belongs_to :phone
end

class Phone < ActiveRecord::Base
has_many :comments, :dependent => :destroy
end
下面是运行的原始SQL

SELECT phones.ccount ,
   comments.*
   FROM phones
   INNER JOIN comments
   ON phones.pnumber = comments.pnumber;
当我在控制器中运行以下命令时

    @phones = Phone.select("phones.ccount, comments.*").joins(:comments).where(:comments => {comments.pnumber => phones.pnumber})
我得到以下错误

undefined local variable or method `comments' for #<FrontPageController:0x00000003c56c70>

如果您对active record语句有任何帮助,我们将不胜感激。

您似乎错误地使用了select。你看过文件了吗

from docs:Second:修改查询的SELECT语句,以便只检索某些字段:

查询的语法应该更像使用标准示例:

l = Location.where(["id = ?", id]).select("name, website, city").first.
l = Location.where(["id = ?", id]).select("name, website, city").first.