构建期间设置的嵌套属性值未保存

Nested attribute values set during build not being saved

我正在尝试构建一些具有特定属性值的嵌套对象。一个listing has_many个订单,一个has_many个订单order_events.

理想情况下,当创建并保存新列表时,也应创建并保存关联的订单(设置 seller_id)和 order_event(设置状态)。

我运行遇到两个问题:

  1. 订单已保存,但seller_id未保存。

  2. order_event根本没有保存

在控制器中,我有:

def new                                                                                                                                                            
  @listing = Listing.new

  @order = @listing.orders.build(seller_id: current_user.id)

  @order_event = @listing.orders.first.order_events.build(state: 'confirmed')
end

def create
    @listing = Listing.new(listing_params)

    respond_to do |format|
      if @listing.save
        format.html { redirect_to manage_path, notice: 'Listing was successfully created.' }
        format.json { render :show, status: :created, location: @listing }
      else    
        format.html { render :new }
        format.json { render json: @listing.errors, status: :unprocessable_entity }
      end
    end
  end

def listing_params
  params.require(:listing).permit(:title, :address, :size, :min_lease, :price, :description, :state, space_ids: [], amenity_ids: [], images_files: [], images_attributes: [:id, :_destroy], orders_attributes: [:id, :_destroy, :start, :end, :seller_id, order_events_attributes: [:id, :_destroy, :state]])
end

有什么想法吗?

在您的创建操作中,尝试像这样分配 seller_id@order_event

def new                                                                                                                                                            
  @listing = Listing.new

  @order = @listing.orders.build
  @order_event = @order.order_events.build
end

def create
  @listing = Listing.new(listing_params)

  @order = @listing.orders.first
  @order.seller_id = current_user.id

  @order_event = @order.order_events.build(state: 'confirmed')

  respond_to do |format|
    if @listing.save
      format.html { redirect_to manage_path, notice: 'Listing was successfully created.' }
      format.json { render :show, status: :created, location: @listing }
    else    
      format.html { render :new }
      format.json { render json: @listing.errors, status: :unprocessable_entity }
    end
  end
end