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

时间:2015-08-23 15:52:59

标签: ruby ruby-on-rails-4 controllers rails-models

我有两个型号的用户和产品。每个用户都可以拥有多种产品。

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 个答案:

答案 0 :(得分:-1)

self.的第六行,将current_user放在product = self.current_user.products.build(product_params) 前面:

var countryApp = angular.module('countryApp', ['ngRoute']);

  countryApp.config(function($routeProvider) {
    $routeProvider.
      when('/', {
        template: '<h1>Home</h1>',
        controller: 'homeCtrl'
      }).

      when('/aboutus', {
        templateUrl: 'aboutus.html',
        controller: 'aboutCtrl'
      }).

      when('/contact', {
        templateUrl: 'cotacts.html',
        controller: 'contactCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
  });

countryApp.controller('homeCtrl', function($scope) {

});

countryApp.controller('aboutCtrl', function($scope) {
     $scope.names = [{name:'venu',number:'22222',sex:'male'},{name:'Aishu',number:'1111',sex:'female'},{name:'Milky',number:'2222',sex:'female'}]




});

countryApp.controller('contactCtrl', function($scope) {
        $scope.greeting = 'Hello, World!';                                    
      $scope.insertContact = function () {



         alert(names);

     }
     $scope.resetContact = function () {

     }
});