ROR Scaffold Destroy redirect_to

时间:2015-05-08 00:28:56

标签: ruby-on-rails ruby path destroy

我实际上已经建立了一个'优惠'脚手架引用用户(设计)和产品。我可以在特定产品页面上添加优惠。但是,我意识到当我尝试删除商品时,它默认重定向到products_url。如何将其重定向回特定产品页面?当我创建评论时,它会重定向到特定的产品页面。删除不会这样做。 我尝试过使用

原始代码

class OffersController < ApplicationController
before_action :set_offer, only: [:show, :edit, :update, :destroy]

def index
 @offers = Offer.all
 end

def show
end

def new
 @offer = Offer.new
 end

 # GET /offers/1/edit
 def edit
 end

 # POST /offers
 # POST /offers.json
 def create
@product = Product.find(params[:product_id])
@offer = @product.offers.new(offer_params)
@offer.user = current_user

respond_to do |format|
  if @offer.save
    format.html { redirect_to @product, notice: 'Offer was successfully created.' }
    format.json { render json: @product, status: :created, location: @offer }
  else
    format.html { render action: "new" }
    format.json { render json: @offer.errors, status: :unprocessable_entity }
  end
  end
 end

 # PATCH/PUT /offers/1
 # PATCH/PUT /offers/1.json
 def update
   respond_to do |format|
     if @offer.update(offer_params)
       format.html { redirect_to @offer, notice: 'Offer was successfully updated.' }
      format.json { render :show, status: :ok, location: @offer }
     else
    format.html { render :edit }
    format.json { render json: @offer.errors, status: :unprocessable_entity }
  end
  end
  end

     # DELETE /offers/1
  # DELETE /offers/1.json
   def destroy
   @offer.destroy
    respond_to do |format|
      format.html { redirect_to product_url, notice: 'Offer was successfully destroyed.' }
      format.json { head :no_content }
    end
   end

  private
    # Use callbacks to share common setup or constraints between actions.
   def set_offer
    @offer = Offer.find(params[:id])
    end

     # Never trust parameters from the scary internet, only allow the white list through.
    def offer_params
      params.require(:offer).permit(:product_id, :priceOffer, :user_id)
   end
 end

我试图修改

def destroy
@offer.destroy
respond_to do |format|
  format.html { redirect_to @product, notice: 'Offer was successfully destroyed.' }
  format.json { head :no_content }
end
end

它实际上显示了我的错误。 26实际上是offer_id。它实际上应该重定向到http://localhost:3000/products/18。它向我展示了如下提取的来源。

Couldn't find Product with 'id'=26
def set_product
  @product = Product.find(params[:id])
end

3 个答案:

答案 0 :(得分:0)

我不确定我是否理解了这个问题,但我认为您只需要将产品的ID作为附加参数传递,例如:

= link_to 'destroy', offer_path(@offer, product_id: @product.id), method: :delete

然后在你的控制器中使用

redirect_to product_path(params[:product_id])

答案 1 :(得分:0)

在destroy方法中执行此操作。

产品=@offer.product

redirect_to:product

您使用的@product未设置。所以我们需要在这里设置product_id。 这就是为什么我们通过关系

从商品变量中获取产品ID的原因

答案 2 :(得分:0)

你在set_product中所做的只是使用params [:id]来查找产品,但是当你调用destroy时,params [:id]引用了offer_id,这就是你得到RecordNotFoundError的原因。我想你可以写这个。

def set_product
  # maybe you should judge whether @product is nil or not
  @product = @offer.product
end