[英]Undefined method error with has_one association
我有一个商店模型和一个用户模型。 逻辑是用户可以有一个商店,而商店可以有一个与之关联的用户,所以我使用has_one: shop
关联。
但是在为新用户创建新商店时出现此错误
#<\\ User:0x007f6f30659068>的未定义方法'shops'是什么意思? 店铺店铺=
我不明白怎么了。 我确定我一定做过一些愚蠢的事情,这是我的代码:
class ShopsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
def new
@shop = current_user.shop.build
end
def create
@shop = current_user.shops.build(shop_params)
@shop.user = current_user
respond_to do |format|
if @shop.save
format.html { redirect_to @shop, notice: 'Shop was successfully created.' }
format.json { render :show, status: :created, location: @shop }
else
format.html { render :new }
format.json { render json: @shop.errors, status: :unprocessable_entity }
end
end
end
private
def shop_params
params.require(:shop).permit(:name, :description, :imageshop, :location, :web, :email, :phone, :business_type, :category)
end
end
class Shop < ApplicationRecord
mount_uploader :imageshop, ImageUploader
belongs_to :user
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :products, dependent: :destroy
has_one :shop
end
我想你需要改变
@shop = current_user.shops.build(post_params)
至
@shop = current_user.build_shop(post_params)
这是因为您指定了一个用户可以拥有一个商店。
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.