Rails 搜索表单 [英] Rails Search Form

查看:43
本文介绍了Rails 搜索表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个跟踪用户和成就(think、xbox live 等)的应用程序.这些表通过连接表链接.我想在我的索引上有一个搜索表单,让用户输入用户名,然后加载一个新页面,其中包含用户获得的所有成就的列表.我不完全确定如何在索引上设置此搜索表单,以实际搜索用户表并在新页面上返回结果.任何帮助将不胜感激.如果您需要更多信息,我很乐意提供.

I'm creating an application that tracks users and achievements (think, xbox live, etc.) These tables are linked via a join table. I would like to have a search form on my index that lets users type in a users name and a new page is loaded with a list of all achievements that user has earned. I'm not entirely sure how to set up this search form, on the index, to actually search the user table and return the results on a new page. Any help would be greatly appreciated. If you require more information then I'll be happy to provide it.

推荐答案

这里有一些骨架代码,可让您根据我从您所说的内容中认为您需要的内容开始.我希望这是有用的.

Here's a bit of skeleton code to get you started based off what I think you need from what you have said. I hope this is useful.

对于搜索位,您可以在索引视图中执行以下操作:

For the search bit you could do something like this in your index view:

<%= form_for User.new, :url => "search" do |f| %>
  <%= f.label :name %>
  <%- f.text_field :name %>
<%- end %>

在您的控制器中:

def search
  q = params[:user][:name]
  @users = User.find(:all, :conditions => ["name LIKE %?%",q])
end

并在您的搜索视图中:

<%-@users.each do |user| %>
  Name: <%=user.name %>

  <%- user.achievements.each do |achievement| %>
    <%= achievement.name %>
  <%- end %>
<%- end %>

当然,您需要确保用户和成就模型正确链接:

You would, of course, need to ensure the users and achievement models are correctly linked:

class User << ActiveRecord::Base
  has_many :achievements

end

这篇关于Rails 搜索表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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