繁体   English   中英

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

[英]Converting a SQL query to Active Record in 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>

任何有关活动记录声明的帮助都将不胜感激

似乎您错误地使用了select()。 您是否阅读过以下文档: http : //apidock.com/rails/ActiveRecord/QueryMethods/select

来自文档:“第二个:修改查询的SELECT语句,以便仅检索某些字段:”

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM