Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails where LIKE子句中的Rails动态属性_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails where LIKE子句中的Rails动态属性

Ruby on rails where LIKE子句中的Rails动态属性,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一个搜索方法,它在参数中接受一个键值对,并通过LIKE查询搜索活动记录模型。但我无法让它工作。它没有正确地接受关键论点 我的方法是这样的: def search(key,value) where('? LIKE ?',key,"%#{value}%") end 它激发的查询是('name'类似于“%air%”),而它应该激发(name类似于“%air%”) 有什么办法可以让它工作吗?像这样试试 def search(key,value) where("#{key} LIKE ?",

我有一个搜索方法,它在参数中接受一个键值对,并通过LIKE查询搜索活动记录模型。但我无法让它工作。它没有正确地接受关键论点

我的方法是这样的:

def search(key,value)
  where('? LIKE ?',key,"%#{value}%")
end
它激发的查询是
('name'类似于“%air%”)
,而它应该激发
(name类似于“%air%”)

有什么办法可以让它工作吗?

像这样试试

def search(key,value)
  where("#{key} LIKE ?","%#{value}%")
end

警告:@MKumar提出的解决方案非常危险。如果
是用户输入,则只允许SQL注入

def搜索(键、值)
其中(“{key}LIKE?”,“%{value}%”)
结束
搜索(“IS_ADMIN==1——”,“”)
哎呀

更好的方法是使用Arel表

def搜索(键、值)
column=Model.arel_table[key.to_sym]#通过符号索引到列中
其中(column.matches(“%#{value}%”)
结束

这无法生成SQL注入。

不安全!见@ven的答案。