我与User和SecurityBadge模型一对一关联。我有一个问题,我无法渲染我的views/security_badges/_form
,因为它生成了复数user_security_badges_path
而不是单数user_security_badge_path
当我访问此链接时:
localhost:3000/users/1/security_badge/new
我在development.log文件中收到了这个消息:
ActionView::Template::Error (undefined method `user_security_badges_path' for #<#<Class:0x00007f888fb456d0>:0x00007f888fccff00>
Did you mean? user_security_badge_path
user_security_badge_url):
1: <%= form_with(model: [@user, security_badge], local: true) do |form| %>
2: <% if security_badge.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security badge from being saved:</h2>
这是在我的_form中:
我很确定问题出在model: [@user, security_badge]
上,它生成的是复数路径而不是单数路径。但是我不知道该如何解决。
<%= form_with(model: [@user, security_badge], local: true) do |form| %>
<% if security_badge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>
<ul>
<% security_badge.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name, autofocus:true, class: "form-control" %>
</div>
<br>
<div class="row float-right">
<div class="col-md-12 actions">
<%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
<%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
</div>
</div>
<% end %>
新视图模板:
<%= render 'form', security_badge: @security_badge %>
用户模型:
class User < ApplicationRecord
has_one :security_badge, dependent: :destroy
end
SecurityBadge模型:
class SecurityBadge < ApplicationRecord
belongs_to :user
end
我的路线:
resources :users do
resource :security_badge
end
我的某些控制器security_badges_controller:
before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
before_action :set_security_badge, only: [:show, :edit, :update, :destroy]
def new
@security_badge = @user.build_security_badge
end
def edit
end
def create
@security_badge = @user.security_badge.new(security_badge_params)
respond_to do |format|
if @security_badge.save
format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
else
format.html { render :new }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:user_id])
end
def set_security_badge
@security_badge = SecurityBadge.find(params[:id])
end
更新
我通过使用url
显式传递单数路径来使它起作用,但是对于非复数的嵌套路由,建议这样做吗?有没有一种方法可以使form_with与嵌套的奇异路线一起使用,或者这是做到这一点的方法?
<%= form_with(model: security_badge, url: user_security_badge_path(@user), local: true) do |form| %>