【问题标题】:Undefined method error with has_one associationhas_one 关联的未定义方法错误
【发布时间】:2019-03-10 17:34:50
【问题描述】:

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

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

# 的未定义方法 '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

【问题讨论】:

    标签: ruby-on-rails devise associations


    【解决方案1】:

    我认为你需要改变

    @shop = current_user.shops.build(post_params)
    

    @shop = current_user.build_shop(post_params)
    

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

    希望对你有帮助!

    【讨论】:

    • 感谢您的回答,但现在在 def new undefined method build' for nil:NilClass 上收到此错误:NilClass`
    • 尝试将 current_user.shop.build 更改为 current_user.build_shop(来自 def new)。更多信息在这里:guides.rubyonrails.org/…
    • 感谢@Alex,它在为其他人编辑您的答案时稍作更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多