gpt4 book ai didi

mysql - 通过表名和变量键检索rails中的所有记录

转载 作者:行者123 更新时间:2023-11-29 18:27:24 25 4
gpt4 key购买 nike

我有一个 Controller ,我向其传递表/模型的名称(:对象)、属性(:键)和搜索条件(:id):

def getAll
obj = params.require(:object)
datarecord = obj.classify.constantize
key=params[:key] + "= :i";
render json: { result: datarecord.find(:all, :conditions => [ key, {:i =>params[:id]}])}
end

不幸的是,我没有得到预期的结果。错误消息是找到 0 条记录,但需要 2 条记录。

例如,我将以下参数传递给我的 Controller :对象:“机会”键:“帐户 ID”编号:2

因此,我想检索机会表中属于 account_id=2 的帐户的所有记录。

知道我的代码有什么问题吗?

谢谢,迈克尔

最佳答案

解决方案:

def getAll
obj = params.require(:object)
datarecord = obj.classify.constantize
render json: { result: datarecord.where(params[:key] => params[:id]) }
end

建议:

def get_all
model = params.require(:model).safe_constantize
conditions = params[:conditions].to_h
records = model.where(conditions)
render json: { result: records }
end
  • 请求示例:
    • 模型=“机会”
    • 条件 = { 'account_id' => 2 }

关于mysql - 通过表名和变量键检索rails中的所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46050883/

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