Rails错误:未定义#的`product'方法。<0x00007faaa8c42700> 你的意思是产品产品=0x00007faaa8c42700>

问题描述 投票:0回答:1

我正在努力开发一个 Shopping application 其中有3种模式,即 User(Devise), ProductBatch. 我做了一个 has_many 之间的联系 UserProduct 并建立了一个 User(signed up in Devise). 然后,我把关联改为 has_and_belongs_to_many 并创建了一个迁移来创建连接表。我按照这个答案 https:/stackoverflow.coma570172419110386。 添加 Productcurrent_user. 然后,我删除了我的用户帐户,并试图注册,但它显示了这样的错误.NoMethodError in Devise::RegistrationsController#createundefined 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

我这是做错了什么。而且我还想把 Product 破坏车体,从车体上的 current_user. 如何做到这一点?

先谢谢你。

ruby-on-rails devise rubygems associations ruby-on-rails-6
1个回答
1
投票

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

删除appmodelsuser.rb文件中的这一行。validates_length_of :product, maximum: 10


0
投票

你的错误是在Devise RegistrationsController的创建方法上做了标记。你可能在那里留下了对user.product的引用,而用户的产品是复数。

© www.soinside.com 2019 - 2024. All rights reserved.