0

I have a model Products that belongs_to a model Store (which has_many products).

When I create a new product for a store, I'm using this url:

/products/new?store_id=4

When a product creation fails validation, I am being redirected to:

/products

Here is the respond_to for this "create" action:

respond_to do |format|
  if @product.save        
    format.html { redirect_to(@product.store, :notice => 'Product was successfully created.') }
    format.xml  { render :xml => @product, :status => :created, :location => @product }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
  end
end

Ideally, I'd like to redirect the user on a failed create back to the exact url as before, namely:

/products/new?store_id=4

Thanks,

Harris

lightyrs
  • 2,809
  • 2
  • 29
  • 32
  • 2
    The answer is in this post, http://stackoverflow.com/questions/1549055/rails-pass-parameters-with-render-action – Rafal Feb 11 '11 at 22:00
  • 1
    Just a design suggesstion (which may or may not apply to you, but worth checking out): Make `store belong_to product`. You can then have RESTful routes such as `/stores/1/products/5`, `/stores/2/products/5`, cos products *might* belong to many stores in the future of your app ? – Zabba Feb 11 '11 at 22:24
  • Appreciate the suggestion Zabba but I'm dealing with stores for specific music artists. So I know for sure that the products of Bob Dylan store will never become the products of Bruce Springsteen store. – lightyrs Feb 11 '11 at 22:43
  • Thanks Rafal -- that post helped but I ended up using a redirect_to with a flash to store the errors. – lightyrs Feb 12 '11 at 03:38

1 Answers1

0

Perhaps this helps?

@store_id = params[:store_id]

respond_to do |format|
  if @product.save        
    format.html { redirect_to(@product.store, :notice => 'Product was successfully created.') }
    format.xml  { render :xml => @product, :status => :created, :location => @product }
  else
    format.html { render :action => "new", :store_id => @store_id }
    format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
  end
end

This is where I got my inspiration.

Community
  • 1
  • 1
Trip
  • 26,756
  • 46
  • 158
  • 277