How to display error messages in a multi-model form with transaction?

后端 未结 5 1264
长情又很酷
长情又很酷 2021-01-23 06:53

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The p

5条回答
  •  鱼传尺愫
    2021-01-23 07:17

    Did you code successfully create a person during the rescue block?

      rescue ActiveRecord::RecordInvalid => exception
          # do something with exception here
          raise ActiveRecord::Rollback
          @organization.users.build if @organization.users.blank?
          render :new and return
    

    This code looks like it will create a new empty User regardless of incorrect validations. And render new will simply return no errors because the user was successfully created, assuming Organization has no Users.

    The control flow of this method has a few outcomes, definitely needs to be broken down some more. I would use byebug and walk through the block with an incorrect Organization, then incorrect name. Then an empty Organization with incorrect User attributes.

提交回复
热议问题