我有两个型号的用户和产品。每个用户都可以拥有多种产品。
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
答案 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 () {
}
});