I am creating an app with a chat function.
The problem is that when I save the rooms table I can't save it due to users validation.
The rooms table and users table have a many-to-many relationship with an intermediate table (room_users) in between.
When saving users, it can be saved without any problem, and the restriction by validation also works as intended. (Force password to mix half-width alphanumeric characters and it works like that.)

I want to save rooms after validating users. How can I solve this? Please professor.

Validation failed: Users is an invalid value
Corresponding source code

■ views/rooms/new.html.erb

  <% = render "tasks/header"%><% = form_with model: @room, local: true do | f |%>                                                ① Please select the person to consult
                                    <% User.all.where.not (id: current_user.id) .each do | user |%>               data-id =<% = user.id% >>              <% = user.nickname%>                          <% end%>                                                        ② Is this the person to consult with?
                                        <input name = "room [user_ids] []" type = "hidden" value =<% = current_user.id% >>          <% # The data-id of .user-bar clicked by the user is set to the value of select-user below by JavaScript operation. %>          <input name = "room [user_ids] []" type = "hidden">                                    ③ Please enter the room name.<br>            Let's name it so that you can understand what the consultation is about.<br>            Example) When is the next meeting scheduled?<br>          <% = f.text_field: room_name, class:'room-name-input', placeholder:'Please enter the room name'%>                        ④ After inputting, click the "Create Room" button to create a room.
                                    <% if @ room.errors.any?%>                  <ul>          <% @ room.errors.full_messages.each do | message |%>            <li class ='error-message'><% = message%></li>          <% end%>        </ul>              <% end%>                <% = f.submit'Create room', class: "add-task-btn"%>      <% end%><% = render "tasks/side"%>

■ models/user.rb

class User</pre>
<p>■ models/room.rb</p>
<pre><code data-language = "Ruby">class Room</pre>
<p>■ models/room_user.rb</p>
<pre><code data-language = "Ruby">class RoomUser</pre>
<strong>What I tried</strong>
<p>(1) Comment out the validation of the problem in user.rb → Both rooms and room_users can be saved normally. (Of course, users are not validated)<br />
(2) Change the validation of the problem in user.rb to a unique constraint → Both rooms and room_users are not saved due to the same error.<br />
③ After applying validation, save users → save. Validation is intended to specify password as a mixture of alphanumeric characters, but it works as it is.<br />
④ Try to prepare binding.pry with the create action of rooms. → params is sending the parameters as intended.</p>
<pre><code>From: /Users/kintarou/projects/good-question/app/controllers/rooms_controller.rb: 9 RoomsController # create:
     7: def create
     8: @room = Room.new (room_params)
 =>9: binding.pry
    10: if @ room.save
    11: redirect_to root_path
    12: else
    13: render: new
    14: end
    15: end
[1] pry (#<RoomsController>)>@room
=>#<Room: 0x00007f843bdd0330 id: nil, room_name: "Next meeting appointment", created_at: nil, updated_at: nil>[2] pry (#<RoomsController>)>Started GET "/ cable" for :: 1 at 2020-11-10 14:42:27 +0900
[2] pry (#<RoomsController>)>params
=>"lqTqiP2G7lc/kKrguWt7DrNNPPYgsAcX4ISbx/kvFe51zWC + PUvWDr6TOdDTn9HHphM1zm1eAQxrvS5gHKXaKQ ==", " ,,

 "room_name" =>"Schedule for next meeting"} permitted: false>, "commit" =>"Create room", "controller" =>"rooms", "action" =>"create"} permitted: false>[3] pry (#<RoomsController>)>@ room.save!
ActiveRecord :: RecordInvalid: Validation failed: Users is an invalid value
from /Users/kintarou/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activerecord- `raise_validation_error'
[4] pry (#<RoomsController>)>

⑤ Server restart/PC restart → The situation does not change.

Supplementary information (FW/tool version, etc.)

ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19]

Please forgive me for the fact that I may not be able to get the point with the first question and there may be missing information.
I would appreciate it if you could teach at the same time.
I look forward to working with you.

  • Answer # 1

    I'm not sure, so it's just a little research.

    If you're having trouble with validationbelongs_to: user, validate: falseI felt that I could avoid it. (API dock: belongs_to)

    : validate
    When set to true, validates new objects added to association when saving the parent object. False by default. If you want to ensure associated objects are revalidated on every update, use validates_associated.

    Howevervalidate: falseButdefaultSo. .. .. I wonder what about

  • Answer # 2

    bin/rails consoleCan I save it after launching and running the following code?

    user_ids = [1, 2]
    room = Room.new (room_name: "Next meeting appointment")
    room.users<<User.where (id: user_ids)

    If you can save it with this, rewriting it like this may work.
    If the above code doesn't work, forget about it because it's wrong.

    def create
      user_ids = params [: room] [: user_ids] # =>["1", "2"]
      @room = Room.new (room_params)
      @ room.users<<User.where (id: user_ids)
      if @ room.save
        redirect_to root_path
      else else
        render: new