【发布时间】:2020-06-17 18:50:14
【问题描述】:
我正在尝试开发一个 Shopping application,它有 3 个模型,即 User(Devise)、Product 和 Batch。我在User 和Product 之间建立了has_many 关联,并创建了User(signed up in Devise)。然后我将关联更改为has_and_belongs_to_many,并创建了一个迁移来创建连接表。我已经按照这个答案https://stackoverflow.com/a/57017241/9110386 将Product 添加到current_user。然后我删除了我的用户帐户并尝试注册,但它显示了这样的错误。
设计中的 NoMethodError::RegistrationsController#create
未定义的方法 `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?
-
这行中出现的错误似乎是:
validates_length_of :product, maximum: 10in user model,users table model 是否有名为product的列? -
@ricks Devise 没有控制器。如何修改默认的 Devise::RegistrationController?
-
@ricks 你能解释一下如何修改控制器,因为我找不到任何用于设计的控制器
标签: ruby-on-rails devise rubygems associations ruby-on-rails-6