【问题标题】:Rails search form- not sure how to get it to work?Rails 搜索表单 - 不确定如何使用?
【发布时间】:2013-04-11 22:12:56
【问题描述】:

我正在尝试在我的 rails 应用程序的主页上添加一个搜索表单,该表单可以搜索候选模型,以查看如果我输入候选模型的名称,它会显示可能候选模型的图片,然后单击他们进入他们的候选页面。

问题:搜索表单显示在主页上,但随后出现路由错误:没有路由匹配 [GET] "/search"

下面是views/home/index.html.erb中的代码:

<%= form_tag("/search", :method => "get") do %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>

搜索控制器:

def index
@candidates = Candidate.search(params[:name])
end

搜索视图(views/search/index.html.erb):

<h1> Here are your search results: </h1>
<% @candidates.each do |candidate| %>
<%= link_to image_tag(candidate.picture, :size => "100x100", :alt => "Edit Entry"),     candidate%>
<% end%>

候选模特:

def self.search(name)
 where('name LIKE ?', "%#{name}%")
end

耙子路线:

candidates_show GET    /candidates/show(.:format)     candidates#show
candidates_new GET    /candidates/new(.:format)      candidates#new
donations_index GET    /donations/index(.:format)     donations#index
home_index GET    /home/index(.:format)          home#index
import_candidates POST   /candidates/import(.:format)   candidates#import
candidates GET    /candidates(.:format)          candidates#index
POST   /candidates(.:format)          candidates#create
new_candidate GET    /candidates/new(.:format)      candidates#new
edit_candidate GET    /candidates/:id/edit(.:format) candidates#edit
candidate GET    /candidates/:id(.:format)      candidates#show
PUT    /candidates/:id(.:format)      candidates#update
DELETE /candidates/:id(.:format)      candidates#destroy
root        /                              home#index

【问题讨论】:

  • 你有什么问题?
  • 对不起,我编辑了一点!
  • 看起来您可能正在使用家庭控制器,但搜索代码在您的搜索控制器中。也许将该搜索方法移至您的家庭控制器。需要将自己更改为候选人
  • 我仍然遇到同样的路由错误。我尝试添加一条搜索路线,但不确定要匹配什么...

标签: ruby-on-rails search rails-routing


【解决方案1】:

您的表单标签指向search,但没有名为search 的路由。就像上面建议的那样,要么将 index 方法从你的搜索控制器移动到你的主控制器,要么在你的 routes.rb 中添加 search 路由,比如

match "search" => "search#index"

【讨论】:

  • 我仍然遇到同样的路由错误。我尝试添加一条搜索路线,但不确定要匹配什么...
  • 成功了!问题:搜索无法有效过滤候选人(它只显示所有候选人的照片)。我在用 SQL 命令做什么?
  • 查看您的日志文件以查看在您的应用根文件夹中tail -f log/development.log 执行了哪些查询
  • Yossarian,我应该在搜索模型中有候选搜索代码(即所有 SQL 内容)吗?我觉得这就是搞砸了。输出内容如下: Started GET "/assets/home.js?body=1" for 127.0.0.1 at 2013-04-11 15:43:04 -0700 Served assets /home.js - 304 Not Modified (0ms)在 2013 年 4 月 11 日 15:43:04 -0700 为 127.0.0.1 开始 GET "/assets/application.js?body=1" 服务资产 /application.js - 304 未修改 (0ms) 开始 GET "/assets/ Moore.jpg”为 127.0.0.1 在 2013-04-11 15:43:04 -0700 服务资产 /Moore.jpg - 304 未修改 (0ms)
  • 现在在候选模型中拥有它,这意味着 where clause 将在候选表上执行。所以它看起来像:select * from candidates where candidate.name like %whut%
猜你喜欢
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多