Ruby on Rails Saving in two tables from one form

后端 未结 3 844
失恋的感觉
失恋的感觉 2020-12-10 09:43

I have two models Hotel and Address. Relationships are:

class Hotel
  belongs_to :user
  has_one    :address
  accepts_nested_attributes_for :address
         


        
3条回答
  •  被撕碎了的回忆
    2020-12-10 10:20

    You should not build address again

    class HotelsController < ApplicationController
      def new
        @hotel = Hotel.new
      end
    
      def create
        @hotel = current_user.hotels.build(hotel_params)
        # address = @hotel.address.build 
        # the previous line should not be used
        if @hotel.save      
          flash[:success] = "Hotel created!"
          redirect_to @hotel
        else
          render 'new'      
        end    
      end
    

提交回复
热议问题