2015-08-23 66 views
0

我有两个模型用户和产品。每个用户可以有多个产品。rails has_many创建关联对象时未定义的方法

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 

我想补充的产品为用户 enter image description here

,但我得到这个错误 enter image description here

回答

1

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

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

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

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

current_user是Authenticable.rb中的函数。只是更新了问题。 –

+0

Ruby有'self',而不是'this'。 –

相关问题