我正在尝试构建一些具有特定属性值的嵌套对象。列表has_many
订单和订单has_many
order_events。
理想情况下,创建并保存新列表时,应创建并保存关联订单(设置为seller_id)和order_event(设置状态)。
我遇到两个问题:
订单已保存,但卖家名不是。
根本不保存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
有什么想法吗?
答案 0 :(得分:0)
在您的创建操作中,尝试分配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