У меня прямая связь с моделями 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| %>