Renegade
Renegade

Reputation: 233

Rails 3 - How To Pass Object ID With Link

Rails 3 ruby 1.9

I am trying to pass a "products" id to a "Details" page and get error "Couldn't find Product without an ID"

This is the link in my browser address bar:

 http://localhost:3000/performance_details?product_id=8

My Controller

class ProductsController < ApplicationController
 def performance_details
  @title = "Performance Details"
  @products = Product.find(params[:id])
end

The view that's passing the object ID

 <%=link_to 'Details', details_path(product_id: product) %>

The view receiving the object ID

 <%@products.each do |product| %>
 Do some stuff with products.....%>
 <%end%>

Routes File

 match 'details' => "products#details"

Upvotes: 0

Views: 274

Answers (4)

Joe Kennedy
Joe Kennedy

Reputation: 9443

Change the @product line in your products controller to the following:

@product = Product.find(params[:product_id])

From your comment below, you're only finding one product (note the change from plural @products to singular @product, so you don't want to use each. Change this:

<%@products.each do |product| %>
  Do some stuff with products.....%>
<%end%>

To just do things with @product, rather than product. So get rid of the outer block, and only use @product. I'd overall recommend the refactoring given in Robin's answer.

Upvotes: 1

svarione
svarione

Reputation: 61

You don't have id in your params. According to your URL /performance_details?product_id=8, your id is in a variable called product_id.

Upvotes: -1

Robin
Robin

Reputation: 21884

That's probably how you should do it:

# routes
resources :products do
  member do
    get :performance_details
  end
end

-

# view
# your url will be /products/:id/performance_details
<%=link_to 'Details', performance_details_product_path(product) %>

-

# controller
class ProductsController < ApplicationController
  def performance_details
    @title = "Performance Details"
    @product = Product.find(params[:id])
  end
end

Upvotes: 3

Max Al Farakh
Max Al Farakh

Reputation: 4476

Your parameter name is product_id, not just id. Here is how your controller should look like:

class ProductsController < ApplicationController
 def performance_details
  @title = "Performance Details"
  @products = Product.find(params[:product_id])
end

Upvotes: 3

Related Questions