【发布时间】:2020-01-22 09:38:16
【问题描述】:
我为localhost:3000/clients/new 的客户提供了一个名为new.html.erb 的视图。我验证它是否有错误。如果出现错误,我会再次渲染新视图以显示所有错误。问题是它在我的浏览器中显示为localhost:3000/clients,而不是localhost:3000/clients/new。这是为什么? “渲染”不应该不改变 URL 的任何内容吗?这会在我刷新页面时出现问题,因为我没有“索引”视图并且它触发了错误,而不是按预期显示“新”视图。
new.html.erb
<% if @client.errors.any? %>
<div class="alert alert-danger">
<h4 class="alert-heading">Error</h4>
<% @client.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
</div>
<% end %>
<%= form_for @client, url: clients_path, remote: false do |f| %>
<div class="form-group row"><label class="col-sm-2 col-form-label">*Name</label>
<div class="col-sm-3">
<%= f.text_field :name, class:"form-control" %>
<% if @client.errors[:name].any? %>
<script>$('#client_name').css('border-color', 'red');</script>
<% end %>
</div>
</div>
<div class="col-sm-4 col-sm-offset-2">
<%= f.submit "Submit", id:"submit", class: 'btn btn-primary btn-sm'%>
<%= link_to "Cancel", controller:"mainpages", action:"index", :html=>{:class=> "btn btn-primary btn-sm"}%>
</div>
<% end %>
clients_controller.rb
def new
@client = Client.new
end
def create
@client = Client.new(client_params)
if @client.save
return redirect_to :root
end
render 'new'
end
routes.rb
root to: "mainpages#index"
get '/mainpages', controller: 'mainpages', action: 'index'
get '/planes', controller: 'planes', action: 'planes'
resources :clients
resources :planes
client.rb
class Client < ApplicationRecord
validates :name, presence: true
end
【问题讨论】:
标签: ruby-on-rails ruby