前提
projectアプリを作成しており、projectテーブルとuserテーブルの関係が多対多なので中間テーブルとしてaffiliationテーブルを作成しています。formから投稿をすると以下のエラー分が表示されます。
Validation failed: Users is invalid
実現したいこと
projectテーブルとaffiliationテーブルにそれぞれデータが保存されるようにしたいです。
発生している問題・エラーメッセージ
Validation failed: Users is invalid
該当のソースコード
app>views>projects>new.html.erb
<div class="select-project-member"> <div class="project-member-text"> <span>プロジェクト参加者</span> </div> <select name="project[user_ids][]"> <option value="">プロジェクト参加者を選択してください</option> <% User.where.not(id: current_user.id).each do |user| %> <option value=<%= user.id %>><%= user.nickname %></option> <% end %> </select> <input name="project[user_ids][]" type="hidden" value=<%= current_user.id %>> </div>
app>models>user.rb
class User < ApplicationRecord extend ActiveHash::Associations::ActiveRecordExtensions belongs_to :sex has_many :affiliations has_many :projects, through: :affiliations
app>models>project.rb
class Project < ApplicationRecord has_many :affiliations has_many :users, through: :affiliations has_one_attached :image
app>models>affiliation.rb
class Affiliation < ApplicationRecord belongs_to :user belongs_to :project end
app>controllers>projects_contoroller.rb
def new @project = Project.new redirect_to new_user_session_path unless user_signed_in? end def create @project = Project.new(project_params) if @project.save! redirect_to root_path else render :new end end private def project_params params.require(:project).permit(:title, :image, :first_detail, :second_detail, :category_id, :select_donation_id, :donation_target_amount, :prefecture_id, user_ids: []) end
試したこと
ターミナル上で@project = Project.new(project_params)のインスタンス変数の中身を確認すると確かにDBに存在しているuser_idが入っており原因がわかりませんでした。ご協力いただけますと幸いです。
補足情報(FW/ツールのバージョンなど)
[1] pry(#<RoomsController>)> params => <ActionController::Parameters {"authenticity_token"=>"IuAWNOyWI/cA5IDnu4P7U0e1QUu9qI7y9Fqtx+nLhTFndjnwQPPQ+/R0NahycKKw6NvkMdRAaUYrXiTEcyp0AQ==", "room"=><ActionController::Parameters {"name"=>"tech camp", "user_ids"=>["2", "6"]} permitted: false>, "commit"=>"Create Room", "controller"=>"rooms", "action"=>"create"} permitted: false> [2] pry(#<RoomsController>)> @room => #<Room:0x00007ff397d29870 id: nil, name: "tech camp", created_at: nil, updated_at: nil> [3] pry(#<RoomsController>)> @room.user_ids => [2, 6]

0 コメント