新手问题 疑问:to_sql 不能用在 controller 中,而只能用在 view 和 console 中?

qqerqqer · May 25, 2012 · Last by lb563 replied at May 25, 2012 · 2519 hits

在 controller 中尝试将 arel AST 转换成原始的 SQL 语句时 (flash[:notice] = @users.to_sql) 一直提示方法 to_sql 没有定义的 error,但是在 view 中是正常的。 难道真的不能在 controller 中使用?rails 小白一枚~~~

你确定你的@users是 relation 对象,能多给点描述信息最好。

#1 楼 @lb563 下面的 UsersController 中的 index action 的代码,不知道够不够详细 def index     @users= User.all     flash[:notice] = @users.to_sql end

#2 楼 @qqerqqer 可以尝试修改代码为:

def index
    @users= User.scoped
    flash[:notice] = @users.to_sql
end

具体可以参考:http://erniemiller.org/2010/05/11/activerecord-relation-vs-arel/

ruby-head > Article.scoped.class
=> ActiveRecord::Relation 
You need to Sign in before reply, if you don't have an account, please Sign up first.