Reputation: 89
am trying to add routes to my rails app but everytime i try to load the index page it returns no route match. my
product.rb
belongs_to :category
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
default_scope { where(active: true) }
end
and here is my category.rb
has_many :products
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
and my routes are setup like this
resources :categories
get '/products/:category_id/:id/', to: 'products#show', as: 'product'
resources :products
in my index page i have it like this
<%= link_to product, class: "card" do %>
<div class="product-image">
<%= image_tag product.productpic.url if product.productpic? %>
</div>
<div class="product-text">
<h2 class="product-title"> <%= product.name %></h2>
<h3 class="product-price">£<%= product.price %></h3>
</div>
<% end %>
<% end %>
but when ever i load the page in my broser i get
No route matches {:action=>"show", :category_id=>#<Product id: 4, name: "virgin hair", price: #<BigDecimal:7fd0af3ffb10,'0.3E3',9(18)>, created_at: "2016-07-19 12:34:34", updated_at: "2016-07-19 12:41:36", slug: "virgin-hair", productpic: "longhair.jpg", pdescription: "this a brazilian virgin hair", active: true, category_id: 2>, :controller=>"products"} missing required keys: [:id]
what am i doing wrong here as i am a novice
Upvotes: 0
Views: 1137
Reputation: 4413
What you're trying to do is called nested routing
.
And this is how you make it right:
# config/routes.rb
resources :categories do
resources :products
end
in your controller:
# app/controllers/products_controller.rb
...
def show
@category = Category.find(params[:category_id])
@product = @category.products.find(params[:id])
end
...
and in your view (to link the above controller action):
<%= link_to 'Awesome Product!', category_product_path(@category, @product) %>
Defining routes like above will let you make paths like this:
/categories/123/products/1
EDIT
To find a record using the name you could do something like this in your controller:
# app/controllers/products_controller.rb
...
def show
@category = Category.find_by!(name: params[:category_id])
@product = @category.products.find_by!(name: params[:id])
end
...
Upvotes: 0
Reputation:
You are passing product object in place of category_id. Try this,
:category_id => product.category_id
Upvotes: 1