[英]Search form_tag not working Ruby on Rails
我真的被卡住了......这似乎很简单,但我真的在这里错过了一些东西......所以,我正在构建一个产品展示页面。 我想创建一个表单字段,在输入邮政编码时返回用户的 State。
这是我的表格,它是show.html.erb。 我希望信息也出现在此视图中:
<%= 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>
这是我的 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
它没有给我任何错误,但信息只是没有显示在视图上......而且@uf 值为零。
您的表格 url 是问题所在。 它应该是这样的: <%= form_tag uf_search_products_path, method: :get do %>
并确保您在产品收集路线中添加了get:uf_search
。
人们!
实际上问题出在 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
我不确定这是否是一个好习惯,因为我才刚刚开始,但它奏效了:谢谢大家! :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.