在Rails 4中将SQL查询转换为Active Record

时间:2013-11-20 01:43:11

标签: sql activerecord ruby-on-rails-4

这是我的两个模特

class Comment < ActiveRecord::Base
belongs_to :phone
end

class Phone < ActiveRecord::Base
has_many :comments, :dependent => :destroy
end

这是表的架构

ActiveRecord::Schema.define(version: 20131119231249) do

create_table "comments", force: true do |t|
t.string   "username"
t.string   "ipaddy"
t.text     "pcomments"
t.string   "company"
t.string   "calltype"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "pnumber"
t.string   "source"
end

create_table "phones", force: true do |t|
t.integer  "pnumber"
t.text     "mrcomment"
t.integer  "ccount"
t.datetime "created_at"
t.datetime "updated_at"
end
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>

非常感谢任何有关活动记录声明的帮助

1 个答案:

答案 0 :(得分:0)

好像你错误地使用了select()。您是否阅读过文档:http://apidock.com/rails/ActiveRecord/QueryMethods/select

来自docs的

:“第二:修改查询的SELECT语句,以便只检索某些字段:”

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

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