gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:00:09 24 4
gpt4 key购买 nike

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

我只想转换带有“@available_deal =Deal where...”的行

app/controllers/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
respond_to do |format|
format.js
end
end

感谢反馈编辑

我进入本地控制台,将查询复制/粘贴到我的文件中,然后将数字替换为我的变量,例如 (@deal.id)

所以现在我有:

app/controllers/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

但是我得到一个错误:

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 = ...
... ^
....

最佳答案

您可以在执行代码时只看一下 Rails 控制台。在那里你应该找到一个看起来有点像的条目

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

SQL中对应的行。

编辑:

您似乎想在您的 ruby​​ 代码中注入(inject)原始 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"

关于ruby-on-rails - 将 ActiveRecord 语句转换为 postgresql 查询 - Rails 4/postgresql 9.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com