私は現在Rails 6アプリケーションに取り組んでいます。私は以下の協会を持っています。ユーザーにはプロファイルがあり、プロファイルはユーザーに属します。ユーザーのプロファイルを編集すると、ユーザーのプロファイルが 2 つになりました。ユーザーごとに 1 つのプロファイルのみを使用したいと考えています。
編集フォーム: profile/edit.html.erb
<%= form_for @profile do |f| %>
<div class="form-group">
<%= f.label :avatar %>
<%= f.file_field :avatar, as: :file, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :full_name, 'Full Name' %>
<%= f.text_field :full_name, autofocus: true, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :city, 'City' %>
<%= f.text_field :city, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :bio, 'Bio'%>
<p> Why did you join ArtsySpace?
What should other people here know about you?
</p>
<%= f.text_field :bio, class: "form-control"%>
</div>
<div class="form-group">
<%= f.submit "Edit profile", class: "btn btn-primary" %>
</div>
<% end %>
コンソールから、ユーザー 1 に 2 つのプロファイルがあることがわかります。プロファイルがどのように作成されたのかわかりませんが、プロファイルコントローラーから作成メソッドを実行した可能性がありますが、間違いはありませんが、これが起こらないようにしたいと思います。ユーザーに属するプロファイルが 1 つだけであることの検証はありますか?
class ProfilesController < ApplicationController
def new
@profile = current_user.build_profile
end
def create
@profile = current_user.create_profile(profile_params)
@profile.avatar.attach(params[:profile][:avatar])
if @profile.save
redirect_to @post
else
render 'new'
end
end
def show
@profile = Profile.find(params[:id])
end
def edit
@profile = current_user.profile
end
def update
@profile = current_user.profile
if @profile.update!(profile_params)
redirect_to @profile, notice: 'Profile was successfully updated.'
else
render :edit
end
end
def delete
@profile = current_user.profile.find(params[:id])
@profile.destroy
end
private
def profile_params
params.require(:profile).permit(:full_name, :city, :bio, :avatar)
end
end
問題がルートの構成方法に起因するかどうかはわかりませんか?
Rails.application.routes.draw do
devise_for :users
devise_scope :users do
resources :profiles, only: [:edit, :update]
end
resources :profiles, only: [:show]
resources :posts do
resource :comments, only: %i[show new create edit update]
end
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :posts
has_one :profile
accepts_nested_attributes_for :profile
end
以下のスニペットから、ユーザーが user_id に対して 2 つのプロファイルを持っていることがわかります。
[#<Profile id: 3, user_id: 1, full_name: "steven ", city: "diego ", bio: "Because im ", created_at: "2019-06-12 23:11:49", updated_at: "2019-06-16 18:49:22">, #<Profile id: 4, user_id: 1, full_name: "andrew", city: "Tony", bio: "because i know ", created_at: "2019-06-12 23:12:35", updated_at: "2019-06-16 18:51:22">]
問題がどこから来たのかわかりません。