Search code examples
ruby-on-railsdeviserubygemsassociationsruby-on-rails-6

Rails error : undefined method `product' for #<User:0x00007faaa8c42700> Did you mean? products products=


I am trying to develop a Shopping application which has 3 models namely User(Devise), Product and Batch. I've made an has_many association between User and Product and created a User(signed up in Devise). And then I changed the association into has_and_belongs_to_many and created a migration to create the join table. I've followed this answer https://stackoverflow.com/a/57017241/9110386 to add the Product to current_user. Then I deleted my User account and tried to sign up but it shows an error like this. NoMethodError in Devise::RegistrationsController#create undefined method `product' for # Did you mean? products products=

User model:


class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  has_and_belongs_to_many :products, :dependent => :destroy
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates_length_of :product, maximum: 10
end

Product model:

class Product < ApplicationRecord
  belongs_to :batch
  has_and_belongs_to_many :user
  validates :name, presence: true
  validates_associated :user

end

Product Controller

class ProductsController < ApplicationController
  before_action :authenticate_user!

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def edit
  end

  def create
  end

  def update 
  end

  def destroy
  end

  def add_cart
    product = Product.find(params[:product_id])
    #current_user.products << product
    #current_user.products << product unless current_user.products.include?(product)
    if current_user.products.include?(product)
      redirect_to products_path, notice: "Already in your cart"
    else
      current_user.products << product
      redirect_to products_path, notice: "Added to cart"
    end
  end

end

What am I doing wrong here. And I also want to remove the Product from the cart by destroying it from the current_user. How to do that?

Thanks in advance.


Solution

  • You have left behind an old validation in your user model.

    Delete this line in the app/models/user.rb file validates_length_of :product, maximum: 10