Felipe Ponce Espinosa Felipe Ponce Espinosa - 1 month ago 17
Ajax Question

Basic rails crud in ajax with devise

I have a basic CRUD in rails and ajax, but I need to integrate Devise gem, when adding devise gem to my project and test the CRUD, I get this error:

Controller error view

code inspector error in browser

the controller code in rails 4.2:

class ProductsController < ApplicationController

before_action :authenticate_user!
before_action :product_find, only: [:show, :update, :destroy, :edit]

def index
@products = Product.all.order('created_at DESC')
end

def show

end

def new
@product = Product.new

respond_to do |format|
format.html { render layout: false }
format.json { render json: @product }
format.js
end

end

def create
@product = current_user.products.build(product_params)
respond_to do |format|
if @product.save
format.json { render :show, status: :created, location: @product}
format.js
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
format.js
end
end
end

def edit

end

def update
@product = Product.update(params[:id], product_params)
end

def destroy
@product.destroy
end

private

def product_find
@product = Product.where(id: params[:id]).first
end

def product_params
params.require(:product).permit(:name, :quantity, :price)
end
end


The user can connect without problems, the error occurs when I create a new product with the registered user

what am I doing wrong?

I think the error may be in the CREATE and NEW method

thank!

Answer

Have you set up the associations correctly for your models? The error undefined method 'products' for <User> suggests that you haven't.

# user.rb
has_many :products

# product.rb
belongs_to :user

Make sure you also have a user_id field on the Product model.