Ruby on rails 搜索表单_标记在Ruby on Rails上不起作用
我真的被卡住了。。。这似乎很简单,但我真的错过了一些东西这里。。。 所以,我正在构建一个产品展示页面。我想创建一个表单字段,在输入zipcode时返回用户的状态 这是我的表格,它是show.html.erb。我希望信息也显示在此视图中:Ruby on rails 搜索表单_标记在Ruby on Rails上不起作用,ruby-on-rails,json,parsing,search,model-view-controller,Ruby On Rails,Json,Parsing,Search,Model View Controller,我真的被卡住了。。。这似乎很简单,但我真的错过了一些东西这里。。。 所以,我正在构建一个产品展示页面。我想创建一个表单字段,在输入zipcode时返回用户的状态 这是我的表格,它是show.html.erb。我希望信息也显示在此视图中: <%= form_tag product_path, method: :get do %> <%= text_field_tag :cep, params[:cep], class: "form-control mr-2
<%= 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>
这是我的控制器:
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
class ProductsController
它没有给我任何错误,但信息只是没有显示在视图上。。。@uf值为零。您的表单url就是问题所在。应该是这样的:
并确保在产品收集路线中添加了get:uf\u search
。人员
实际上问题出在控制器上。。。我做到了这一点,并且它按照我的预期工作:
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
class ProductsController
我不确定这是否是一个好的做法,因为我才刚刚开始,但它奏效了!谢谢大家!:) 这里没有问题。我认为表单url有问题。我猜这个请求不会用于uf_搜索操作。检查表单url和routes.rb。