Rails:用户如何将数据输入到Active Record查询中? [英] Rails: How can a user input data into an Active Record Query?

查看:94
本文介绍了Rails:用户如何将数据输入到Active Record查询中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了Active Record查询的API,但似乎没有为用户提供一种实际输入搜索数据的方法。我想我可以通过某种方式link_to包含查询代码的方法,但是我如何使用特定的搜索参数?假设我只想按名称搜索一个模型的匹配实例。

I read through the API for Active Record Querying, but it doesn't seem to include a method for the user to actually input search data. I assume I could somehow link_to a method which contains the query code, but how could I use specific search params? Let's say I only want to search by name for matching instances of one model.

预先感谢!

推荐答案

简单的方法是

Model.find(:all,:conditions => ['name LIKE?',%#{search}%]])

在视图中

<% form_tag projects_path, :method => 'get' do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

在控制器中

def index
  @projects = Project.search(params[:search])
end

在模型中

def self.search(search)
  if search
    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

这篇关于Rails:用户如何将数据输入到Active Record查询中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆