【发布时间】:2017-02-20 02:57:11
【问题描述】:
我的 rails 应用程序没有按预期路由。控制器中的搜索方法是显示。我已将代码缩减为最少的组件,并按照建议将它们发布在这里。
Rails.application.routes.draw do
resources :backups
get 'backups/search' => 'backups#search'
resources :components
resources :backup_media
end
class Component < ActiveRecord::Base
has_many :backups
has_many :backup_media, :through => :backups
end
class BackupMedium < ActiveRecord::Base
has_many :backups
has_many :components, :through => :backups
end
class Backup < ActiveRecord::Base
belongs_to :component
belongs_to :backup_medium
# value to match either the name of the component or backup_medium
def self.search(value)
tables = "backups, components, backup_media"
joins = "backups.backup_medium_id = backup_media.id and components.id = backups.component_id"
c = find_by_sql "select * from #{tables} where components.name like '%#{value}%' and #{joins}"
b = find_by_sql "select * from #{tables} where backup_media.name like '%#{value}%' and #{joins}"
c.count > 0 ? c : b
end
end
class BackupsController < ApplicationController
def search
@backups = Backup.search(params[:search])
render 'index'
end
def index
@backups = Backup.all
end
def show
# this would normally be the code to show an individual backup
# but I'm re-using the code from index because the routing is broken
@backups = Backup.all
end
end
视图/备份/_search.html.erb
<%= form_tag backups_search_path, :method => 'get' do %>
<%= label_tag(:search, "Search for:") %>
<%= text_field_tag :search, params[:search], {:placeholder => 'Component or Media' }%>
<%= submit_tag "Search", :name => nil %>
<% end %>
视图/备份/index.html.erb
<h1>Listing Backups</h1>
<p id="notice"><%= notice %></p>
<%= render :partial => 'search' %>
<table>
<tr>
<th>id</th>
<th>component_id</th>
<th>backup_medium_id</th>
</tr>
<% @backups.each do |backup| %>
<tr>
<td><%= backup.id %></td>
<td><%= backup.component.name %></td>
<td><%= backup.backup_medium.name %></td>
</tr>
<% end %>
</table>
views/backups/show.html.erb 是从 index.html.erb 复制而来,因为它错误地接收了搜索结果
<h1>Show Backup</h1>
<p id="notice"><%= notice %></p>
<%= render :partial => 'search' %>
<table>
<tr>
<th>id</th>
<th>component_id</th>
<th>backup_medium_id</th>
</tr>
<% @backups.each do |backup| %>
<tr>
<td><%= backup.id %></td>
<td><%= backup.component.name %></td>
<td><%= backup.backup_medium.name %></td>
</tr>
<% end %>
</table>
欢迎提出改进搜索方法的建议。
如上所述,执行搜索后,渲染的是show.html.erb,而不是search.html.erb
有关工作演示(由于此处的建议提供了更好的代码),请参阅 https://github.com/pamh09/rails-search-demo
【问题讨论】:
-
发布表格和完整日志
-
这可能是您的视图、控制器或路由文件中的错误。调试你的代码的口头描述真的很难:) 你能否编辑你的问题,并向我们展示每个文件的相关 sn-p,以便我们确定它是哪个。
标签: ruby-on-rails