Я пытаюсь изменить свою ассоциацию моделей с has_many (которая работает) на has_one, но у меня возникают проблемы.
, когда я перехожу к:
localhost:3000/users/1/security_badge/new
я получаю это в логах
NoMethodError (undefined method `new' for nil:NilClass):
Модель пользователя:
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.security_badge.new
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
Обновление
это в моей _form:
<%= 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 %>