0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

中間テーブルに保存する時に、バリデーションエラーが発生した。

Posted at

中間テーブルにidsで配列の処理を行おうとしたらバリデーションエラーが出た

userテーブル

Column Type Options
name string null: false
email string null: false
password string null: false

roomテーブル

Column Type Options
name string null: false

room_userテーブル

Column Type Options
user references null: false, foreign_key: true
room references null: false, foreign_key: true
# viewの記述
<select name="room[user_ids][]">
  <option value="">チャットするユーザーを選択してください</option>
  <% User.where.not(id: current_user.id).each do |user| %>
    <option value=<%=user.id%>><%= user.name %></option>
  <% end %>
</select>
<input name="room[user_ids][]" type="hidden" value=<%= current_user.id %>>

# controllerの記述

  def create
    @room = Room.new(room_params)
    if @room.save
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def room_params
    params.require(:room).permit(:name, user_ids: [])
  end
end

ここまでの記述に関しては、問題なく動作するので、変更することはなかった。

急に中間テーブルにuser_id保存ができなくなった。

原因はわからないが、全く関係ない作業をしているときに急にバリデーションエラーが発生し、値が保存できなくなりRoomモデルも保存できなくなった。

解決した方法

理由がわからないので、少し強引なやり方かもしれないが、解決する方法がこれしかなかったので、これでうまく動作してくれました

  has_many :room_users
  has_many :users, through: :room_users, validate: false
# validate: false 追記

バリデーションを行わない記述をすることで、中間テーブルに値を配列で渡し、うまく保存することができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?