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
current_user是Authenticable.rb中的函數。只是更新了問題。 –
Ruby有'self',而不是'this'。 –