我还是Rails的新手,试图解决我理解的更高级别的问题。我的应用程序需要接受用户输入的代码(散列事件代码唯一到事件),然后将其重定向到特定事件的显示页面(如果找到)。如果未找到,则显示错误div
它不是在我测试时抛出错误,而是应该如此,它只是指向一个通用/显示页面。我已经从大约十几个其他的Stack帖子和教程拼凑了这个,而没有一个已经证明了我需要的那种功能。我需要的是,当这个表单提交时,它需要在控制器中运行一些试图找到该特定对象的东西,如果成功则运行重定向到它。在进行故障排除时,我在控制器中拉出了重定向线,发现它甚至没有运行,还有其他东西指向/ show。如何让我的表单只是问我的方法该做什么?自定义路线是正确的方法吗?
现在,我的表单看起来像这样:
<h2><br/>Input your event code below<br/></h2>
<p>
<form action="<%= lookup_path(:code) %>" method="get" >
<%= text_field_tag( :code, nil, class: "input_field") %>
<%= submit_tag "Submit", :name => nil, :class =>"submit_button" %>
</form>
</p>
<div id="errorbar">
<%= @error_bar %>
</div>`
我的控制器完全是这样的:
class EventController < ApplicationController
def index
end
def lookup
begin
an_event = Event.where(:event_code =>params[:code])
rescue ActiveRecord::RecordNotFound
@error_bar = "Code not found"
end
end
end
就我路线的相关部分而言:
resources :event do
resources :room
end
get 'event/:event_code' => 'event#lookup', as: :lookup
耙路线:
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
root GET / welcome#index
event_room_index GET /event/:event_id/room(.:format) room#index
POST /event/:event_id/room(.:format) room#create
new_event_room GET /event/:event_id/room/new(.:format) room#new
edit_event_room GET /event/:event_id/room/:id/edit(.:format) room#edit
event_room GET /event/:event_id/room/:id(.:format) room#show
PATCH /event/:event_id/room/:id(.:format) room#update
PUT /event/:event_id/room/:id(.:format) room#update
DELETE /event/:event_id/room/:id(.:format) room#destroy
event_index GET /event(.:format) event#index
POST /event(.:format) event#create
new_event GET /event/new(.:format) event#new
edit_event GET /event/:id/edit(.:format) event#edit
event GET /event/:id(.:format) event#show
PATCH /event/:id(.:format) event#update
PUT /event/:id(.:format) event#update
DELETE /event/:id(.:format) event#destroy
lookup GET /event/:event_code(.:format) event#show
答案 0 :(得分:0)
解决方案:
应用/视图/活动/ index.html.erb 强>
<h2><br/>Input your event code below<br/></h2>
<p>
<form action="<%= lookup_path(:code) %>" method="get" >
<%= text_field_tag( :code, nil, class: "input_field") %>
<%= submit_tag "Submit", :name => nil, :class =>"submit_button" %>
</form>
</p>
应用/控制器/ event_controller.rb 强>
class EventController < ApplicationController
............
def show
@an_event = Event.where(:event_code =>params[:code])
end
end
应用/视图/活动/ show.html.erb 强>
<% if @an_event.present? %>
<!-- show event -->
<%= @an_event.name %>
<% else %>
<!-- message with error -->
<% end %>
看看这个
<强>配置/ routes.rb中强>
event GET /event/:id(.:format) event#show
.....
lookup GET /event/:event_code(.:format) event#show
重复路线。将lookup
重命名为show
。删除lookup
路线。