我正在使用this gist在我的Rails应用中构建自动完成功能。
我正在Shoe
模型属性中保存记录,如下所示
"nike air, nike steam,nike softy ,nike strength" #comma separated words
我的控制器代码在
之下def shoes
shoes_list = []
shoes = Shoe.all
shoes.each do |shoe|
shoes_list << shoe.model.split(',')
end unless shoes.blank?
if params[:term]
like = "%".concat(params[:term].concat("%"))
# shoes = Shoe.where("model like ?", like)
# **How i make like query to "shoes_list" same like above commented line?**
else
shoes = Shoe.all
end
list = shoes.map { |u| Hash[id: u.id, label: u.model, model: u.model] }
render json: list
end
如何以json格式呈现它?
答案 0 :(得分:0)
最后这段代码对我有用。
def shoes
shoes_list = []
shoes = Shoe.all
shoes.each do |shoe|
shoes_list << shoe.model.split(',')
end unless shoes.blank?
shoes_list.flatten!
if params[:term]
shoes = shoes_list.grep(Regexp.new( Regexp.escape(params[:term]), "i" ))
else
shoes = shoes_list
end
list = shoes.map {|u| Hash[id: u, label: u, name: u]}
render json: list
end