通过rails

时间:2017-09-05 08:56:09

标签: mysql ruby-on-rails

我有一个控制器,我传递了表/模型的名称(:object),属性(:key)和搜索条件(: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条记录。

例如,我将以下参数传递给我的控制器: 对象:"机会" key:" account_id" id:2

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

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

谢谢, 迈克尔

2 个答案:

答案 0 :(得分:0)

解决方案:

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
  • 请求示例:
    • model ='机会'
    • conditions = {'account_id'=> 2}

答案 1 :(得分:0)

.find将始终返回1条记录(如果我理解正确)datarecord.where(key => params[:id])

where将返回所有记录,您已经拥有密钥和密钥应该为的值