Reputation: 421
My project is about an online shopping site, using Ruby on Rails to buy phones. My Database is User, Product, Phone. I'm trying to create Basket model.
My route:
resources :products do
resources :phone do
resources :baskets
end
end
And my Code is:
class User < ActiveRecord::Base
has_many :baskets
end
class Phone < ActiveRecord::Base
belongs_to :product
has_many :baskets
end
class Basket < ActiveRecord::Base
belongs_to :user
belongs_to :phone
end
When i in the Show action of Product,it Show name of Product and index Phones in this Product,i want to add 1 Phone to Basket,the error is :
No route matches {:action=>"new", :controller=>"baskets", :id=>"38", :product_id=>"30"} missing required keys: [:phone_id]
I think the problem is :
http://localhost:3000/products/30/phone/38
It's Product_id = 30,but not Phone_id = 30,in here just is Id = 30. Someone could help me fix it !
Upvotes: 1
Views: 498
Reputation: 76784
Regardless of whether you got it working (I upvoted @Andrey
's answer), you'll want to consult your routing structure.
Resources should never be nested more than 1 level deep. docs
--
In your case, I am curious as to why you have phones
nested inside products
. Surely a phone is a product?
Further, why are you including resources :baskets
? Surely the basket functionality has nothing to do with whether you're adding a product
, phone
, or anything else?
I would personally do the following:
resources :products, only: [:index, :show] do
resources :basket, path:"", module: :products, only: [:create, :destroy] #-> url.com/products/:product_id/
end
#app/controllers/products/basket_controller.rb
class Products::BasketController < ApplicationController
before_action :set_product
def create
# add to cart
end
def destroy
# remove from cart
end
private
def set_product
@product = Product.find params[:product_id]
end
end
I've implemented a cart (based on sessions) before (here).
I can give you the code if you want; I won't put it here unless you want it. It's based on this Railscast.
Upvotes: 1
Reputation: 52367
resources :products do
resources :phone do
resources :baskets
end
end
means you have to have route like this:
/products/:product_id/phones/:phone_id/baskets/:basket_id(.:format)
Which means, that in link_to
you should pass the phone_id
as well:
link_to 'show basket' product_phone_basket_path(product_id: @product.id, phone_id: @phone.id, basket_id: @basket.id)
link_to 'New basket' new_product_phone_basket_path(product_id: @product.id, phone_id: @phone.id)
Upvotes: 2