In Rails, how can I automatically update a User to own a newly created object of another class within the new object's Create method?

前端 未结 3 1838
旧巷少年郎
旧巷少年郎 2021-01-26 02:35

My application has Users and Dwellings. When a user creates a dwelling, the user becomes the owner

3条回答
  •  不思量自难忘°
    2021-01-26 03:14

    This was an issue with saving the user. I updated my create action in the Dwellings controller to to force a save of the user using user.save! to break the application and get an explicit error. Rails complained of a missing password (and password length) and password_confirmation. I am enforcing a presence validation on both password and password_confirmation as well as a length validation on password in my User model. I updated these validations to be enforced only on create. This solved the issue. With the validations no longer being enforced on user.save, the dwelling_id was successfully added to the user record. The newly implemented code is below.

    #dwellings_controller.rb
    ...
    def create
      @dwelling = current_user.properties.build(params[:dwelling])
    
      if @dwelling.save
        current_user.dwelling = @dwelling
        if current_user.save
          flash[:success] = "Woohoo! Your dwelling has been created. Welcome home!"
        else
          flash[:notice] = "You have successfully created a dwelling, but something prevented us from adding you as a roomie. Please email support so we can try to correct this for you."
        end
        redirect_to current_user
        else
          render 'new'
        end
      end
    ...
    

    --

    #user.rb
    ...
      validates :password, presence: { :on => :create }, length: { minimum: 6, :on => :create }
      validates :password_confirmation, presence: { :on => :create }
    

提交回复
热议问题