我的form_tag
搜索功能存在一些问题,我没有正确地将我重定向到可以查看搜索结果的地方。
它昨天工作正常,点击搜索的提交按钮后,get
控制器pets
方法的search
请求被触发,然后我被重定向到{{1}显示结果的页面。
问题在于,现在当我提交搜索时,它只是刷新页面(results.html.erb
)并且我的参数被传递到URL但是没有显示我搜索的“宠物”。
index.html.erb
在重新定位结果页http://localhost:3000/?utf8=%E2%9C%93&authenticity_token=iDXugIhTyjknCMpPh2P5x7voNMSQ3Y7Aa1HIZPA7xqZ9Oj4CAuVc5eJPqfE1CLwxXAsCebgPuNWqpOk381TlvQ%3D%3D&pets%5Bzip_code%5D=10019&pets%5Bspecies%5D=Cat&pets%5Bbreed%5D=&pets%5Bage%5D=&pets%5Bsex%5D=&pets%5Bsize%5D=&commit=Find+Pets%21
这是我的 宠物 控制器
localhost:3000/results
我的class PetsController < ApplicationController
def index #index page will render search form
@pet = Pet.new
#send form data in params to create
end
def search
@pets = Pet.where(clean_params)
render :results
end
private
def thinned_params
params["pets"].delete_if {|k, v| v.empty?}
end
def clean_params
thinned_params.permit(:species, :zip_code, :sex, :size, :breed, :age)
end
end
欢迎#index:
form_tag
最后......我的 routes.rb
<form class="form-horizontal">
<%= form_tag :controller => 'pets', :action => 'search', :method => 'get' do %>
<%= label_tag('pets[zip_code]', "Zipcode") %>
<%= text_field_tag('pets[zip_code]') %>
<%= label_tag('pets[species]', "Type") %>
<%= select_tag('pets[species]', options_for_select([["Dog","Dog"],["Cat","Cat"],["Rabbit", "Rabbit"], ["Small & Furry","Smallfurry"],["Horse", "Horse"],["Pig", "Pig"],["Reptile", "Reptile"],["Bird", "Bird"],["Barnyard", "Barnyard"]])) %>
<%= label_tag('pets[breed]', "Breed") %>
<%= text_field_tag('pets[breed]', nil, class: 'typeahead') %>
<%= label_tag('pets[age]', "Age") %>
<%= select_tag('pets[age]', options_for_select([["None",""],["Baby","Baby"],["Young","Young"],["Adult", "Adult"], ["Senior","Senior"]])) %>
<%= label_tag('pets[sex]', "Gender") %>
<%= select_tag('pets[sex]', options_for_select([["None",""],["Male","M"],["Female","F"]])) %>
<%= label_tag('pets[size]', "Size") %>
<%= select_tag('pets[size]', options_for_select([["None",""],["Small","S"],["Medium","M"], ["Large", "L"], ["Xtra Large", "XL"]])) %>
<%= submit_tag "Find Pets!" %>
<%end%>
</form>
所以我的问题是为什么我的params传递到URL时它应该只是点击Rails.application.routes.draw do
devise_for :users
resources :users
# resources :pets
root 'welcome#index'
get '/pets' => 'pets#index'
post '/pets/search' => 'pets#search'
resources :favorite_pets
get '/my_pets' => 'users#my_pets'
end
控制器中的search
方法并将我重定向到显示信息的结果页面?
第二个问题,显然,我该怎么做才能解决这个问题?
更新 这是我点击“搜索”按钮时控制台的输出。
pets
Rake Routes https://slack-files.com/files-pub/T02MD9XTF-F041PKBE2-532b801cb1/-.txt
答案 0 :(得分:0)
根据您的路线文件,搜索操作只接受POST(不是GET):
post '/pets/search' => 'pets#search'
这似乎合适,所以只需更改表单操作即可使用POST方法:
form_tag :controller => 'pets', :action => 'search', :method => :post
答案 1 :(得分:0)
您的路线是POST
,但这没有任何意义,您是否正在尝试更新或更换宠物?不,你得到一份宠物清单。您已在表单中调用GET
请求,因此您可以保留该请求并进行更改
post '/pets/search' => 'pets#search'
至get '/pets/search' => 'pets#search'