我正在嘗試構建一些具有特定屬性值的嵌套對象。清單has_many
訂單,以及訂單has_many
order_events。構建期間設置的嵌套屬性值未被保存
理想情況下,創建並保存新列表時,應該創建並保存相關訂單(使用seller_id設置)和order_event(使用狀態設置)。
我遇到了兩個問題:
順序保存,但seller_id不是。
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
任何想法?
您是否在視圖中爲訂單和訂單事件添加了字段到窗體?提交表單時,這些屬性會在創建操作期間丟失並「重建」。 –
不,我最初在表單中使用'hidden_fields'設置值,但是我從表單中刪除了這些值,並將邏輯移至控制器。 –
在這種情況下,您應該在保存列表之前將這兩個分配移至您的創建操作。這樣,它們包含在清單 –