Reputation: 53
I have scaffolded a database for products and there are users which are supposed to create orders by pressing a button next to the product. I don't quite understand what is going on but I get an error message when as a user I try to order a product. Also this product should be displayed on a view of the user where all orders can be seen. I also do not understand how to set this up.
undefined method `orders' for nil:NilClass
My orders_controller:
def create
if @current_user.orders.create(params[:order])
order[product_id] = params[:order][product_id]
else
end
end
My users controller:
def order
@order = Order.new
end
And where the button is supposed to create a product:
><%= button_to 'Order', {:controller => "orders", :action => "create"}, :product_id => product.id, :user_id=> session[:user_id] %>
Upvotes: 1
Views: 1285
Reputation: 101811
If your application requires an order to be linked to a user you should bail early and require authentication. With Devise you would use:
class OrdersController < ApplicationController
before_action :authenticate_user!
# ...
end
This redirects the user to the sign in page if they are not signed in.
Upvotes: 1
Reputation: 7136
If you are using the Devise Ruby gem for authentication then you should remove the @
from @current_user
as Devise provides a helper method for accessing the current user signed in. Just call current_user.orders
.
@current_user
is nil
since you are not assigning it anywhere in the create method.
Check it out here: https://github.com/plataformatec/devise#controller-filters-and-helpers
Upvotes: 0
Reputation: 4200
If you are using Rails authentication gem Devise then you will have a helper method current_user instead @current_user variable. So, you code should be like below,
def create
if current_user.orders.create(params[:order])
# Your code should go here
end
end
Upvotes: 0
Reputation: 36860
If you're using devise to manage your User
then the current user is accessible by a method current_user
. The instance variable @current_user
contains nothing (nil). Note that instance variables you assign in one cycle are not availabel the next time a form is submitted or a link is followed.
Upvotes: 1