rails has_many 创建关联对象时未定义方法

rails has_many undefined method when creating associated objects

我有两个模型用户和产品。每个用户可以拥有多个产品。

User.rb

   class User < ActiveRecord::Base
        validates :auth_token, uniqueness: true
        # Include default devise modules. Others available are:
        # :confirmable, :lockable, :timeoutable and :omniauthable
        devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

        before_create :generate_authentication_token!

        has_many :products, dependent: :destroy

         def generate_authentication_token!
            begin
                self.auth_token = Devise.friendly_token
            end while self.class.exists?(auth_token: auth_token)
         end

    end

Product.rb

class Product < ActiveRecord::Base
    validates :title, :user_id, presence: true
    validates :price, numericality: { greater_than_or_equal_to: 0},
                presence: true

    belongs_to :user    
end

Authenticable.rb

module Authenticable 

    def current_user
        @current_user |= User.find_by(auth_token: request.headers['Authorization'])
    end

products_controller.rb

def create
    //current_user from Aunthenticable.rb
    product = current_user.products.build(product_params)
    if product.save
        render json: product, status: 201, location: [:api, product]
    else
        render json: {errors: product.errors}, status: 422
    end
end

我正在尝试为用户添加产品

但是我得到这个错误

products_controller.rb的第六行,把self.放在current_user前面:

product = self.current_user.products.build(product_params)

当您需要布尔运算符 || 时,您的 current_user 实现使用按位运算符 |。这使得它的计算结果为 true 而不是你的 User。将其更改为:

def current_user
  @current_user ||= User.find_by(auth_token: request.headers['Authorization'])
end