[英]Search form_tag not working Ruby on Rails
I am really stuck... it seems to be simple but I am really missing something here... So, I am building like a product show page.我真的被卡住了......这似乎很简单,但我真的在这里错过了一些东西......所以,我正在构建一个产品展示页面。 I want to make a form field that returns the user's State when input zipcode.
我想创建一个表单字段,在输入邮政编码时返回用户的 State。
This is my form, it is the show.html.erb.这是我的表格,它是show.html.erb。 I want the information to appear also in this view:
我希望信息也出现在此视图中:
<%= form_tag product_path, method: :get do %>
<%= text_field_tag :cep,
params[:cep],
class: "form-control mr-2",
placeholder: "13087560",
maxlength: 8
%>
<%= submit_tag "find", class: "btn-flat my-3 my-0" %>
<% end %>
<p class="product-data"><%= @uf %></p>
This is my controller:这是我的 controller:
class ProductsController < ApplicationController
require 'open-uri'
def index
if params[:query]
@products = Product.search(params[:query])
else
@products = Product.all
end
respond_to do |format|
format.html
format.js
end
end
def show
@product = Product.find(params[:id])
end
def uf_search
if params[:cep]
@uf = JSON.parse(open("https://viacep.com.br/ws/#{params[:cep]}/json/").read)
@uf = @uf['uf']
@uf
end
end
end
It's not giving me any errors, but the information just don't show on the view... and the @uf value is nil.它没有给我任何错误,但信息只是没有显示在视图上......而且@uf 值为零。
Your form url is the problem.您的表格 url 是问题所在。 It should be something like this:
<%= form_tag uf_search_products_path, method: :get do %>
它应该是这样的:
<%= form_tag uf_search_products_path, method: :get do %>
and make sure you have added get:uf_search
inside the products collection routes.并确保您在产品收集路线中添加了
get:uf_search
。
people!人们!
Actually the problem was in the controller... I did this and it worked as I expected:实际上问题出在 controller ... 我这样做了,它按我的预期工作:
class ProductsController < ApplicationController
require 'open-uri'
def index
if params[:query]
@products = Product.search(params[:query])
else
@products = Product.all
end
respond_to do |format|
format.html
format.js
end
end
def show
@product = Product.find(params[:id])
uf_search # inserting the uf_search here solved it
respond_to do |format|
format.html
format.js
end
end
def uf_search
if params[:cep]
url = "https://viacep.com.br/ws/#{params[:cep]}/json/"
address = JSON.parse(open(url).read)
@uf = address['uf']
@city = address['localidade']
end
end
end
I'm not sure if it's a good practice, because I'm just starting but it worked: Thank you all!我不确定这是否是一个好习惯,因为我才刚刚开始,但它奏效了:谢谢大家! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.