has_one 关联的未定义方法错误

Undefined method error with has_one association

我有一个商店模型和一个用户模型。逻辑是用户可以有一个商店,商店可以有一个用户与之关联,所以我使用 has_one: shop 关联。

但是在为新用户创建新商店时出现此错误

undefined method 'shops' for #<\User:0x007f6f30659068> Did you mean? shop shop=

我不明白哪里出了问题。我确定我一定做了一些愚蠢的事情,这是我的代码:

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)

这是因为您指定了一个用户可以拥有一个商店。

希望对您有所帮助!