将ActiveRecord语句转换为postgresql查询 - Rails 4 / postgresql 9.4

时间:2015-09-26 19:57:26

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

如何将以下Active Record查询转换为原始postgresql?

我只想用“@ available_deal = Deal where ...”转换该行

应用程序/控制器/ deals_controller.rb

def show_deals_available
    @deal = Deal.friendly.find params[:id] # no need to turn this into postgresql
    @available_deal = Deal.where('deal_id = ? AND deal_status = ?',
                         @deal.id, "not_yet_taken").first
    @available_deal  = SELECT "deals".* FROM "deals" WHERE (deal_id = @deal.id AND deal_status = 'not_yet_taken') ORDER BY "deals"."id" ASC LIMIT 1


    respond_to do |format|
      format.js 
    end
  end

编辑感谢反馈

我使用我的本地控制台并将查询复制/粘贴到我的文件中,只是将数字替换为我的变量,如(@ deal.id)

所以现在我有:

应用程序/控制器/ deals_controller.rb

SyntaxError - syntax error, unexpected tCONSTANT, expecting keyword_end
...ROM "deals" WHERE (deal_id = @deal.id AND ...
...                               ^
/deals_controller.rb:70: syntax error, unexpected tCONSTANT, expecting ')'
..." WHERE (deal_id = @deal.id AND deal_status = ...
...                               ^
....

但是我收到了一个错误:

android:background=""
android:background="null"

1 个答案:

答案 0 :(得分:2)

执行代码时,您只需查看rails控制台即可。在那里你应该找到一个看起来有点像

的条目
SELECT * FROM deals WHERE deal_id = 1 AND deal_status = 'not_yet_taken'

这是SQL中的对应行。

编辑:

您似乎想在ruby代码中注入原始SQL。对于可以以不同方式解决的问题,这被认为是不好的风格,因为在更新rails或更改数据库后端时可能会中断。然而,如果你真的想采取这种方式,你可以做类似

的事情
Deal.find_by_sql("SELECT \"deals\".* FROM \"deals\" WHERE (deal_id = #{@deal.id} AND click_win_throbber_status = 'not_yet_clicked') ORDER BY \"deals\".\"id\" ASC LIMIT 1"