2015-08-23 7 views
0

У меня есть две модели пользователей и продуктов. Каждый пользователь может иметь несколько продуктов.rails has_many undefined метод при создании связанных объектов

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'. –