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

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

我正在尝试开发一个 Shopping application,它有 3 个模型,即 User(Devise)ProductBatch。我在 UserProduct 之间创建了一个 has_many 关联并创建了一个 User(signed up in Devise)。然后我将关联更改为 has_and_belongs_to_many 并创建了一个迁移以创建连接 table。我按照这个答案 Product 添加到 current_user。然后我删除了我的用户帐户并尝试注册,但它显示了这样的错误。 Devise::RegistrationsController#create 中的 NoMethodError undefined method `product' for # 你的意思是?产品产品=

用户模型:


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

产品型号:

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

end

产品负责人

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

我在这里做错了什么。我还想通过从 current_user 中销毁它来从购物车中删除 Product。怎么做?

提前致谢。

您的错误是标记了 Devise RegistrationsController 的创建方法。您可能在其中留下了对 user.product 的引用,而用户拥有复数形式的产品。

您在用户模型中留下了一个旧的验证。

在app/models/user.rb文件中删除这一行 validates_length_of :product, maximum: 10