UsersController#new 中的 NoMethodError (#<User:0x000000059c50e0> 的未定义方法 'userprofiles' )



我不知道为什么会出现这种错误。我已经在以前的项目(简单的实践项目)中制作了一些嵌套资源,但我不知道为什么不起作用。

错误:

NoMethodError in UsersController#new (undefined method `userprofiles' for #<User:0x000000059c50e0>)

模型

  • user.rbbelongs_to :userprofile
  • user_profile.rbbelongs_to :user

routes.rb

resources :users do
    resources :user_profiles
end

users_controller.rb

class UsersController < ApplicationController
    before_action :authenticate_user!
    before_action :set_userprofile, only: :new
    def index
        if current_user
            @user = User.find_by_email(current_user.email)
            redirect_to :action => "new"
        end
    end
    def new
        @user = User.find(current_user.id)
        @user_profile = @user.userprofiles.new
    end
    private
    def set_userprofile
        @user = User.find(current_user.id)
    end
end

用户模型

 class User < ActiveRecord::Base
    has_many :user_profiles
 end

用户配置文件模型

class UserProfile < ActiveRecord::Base
   belongs_to :user
end

在控制器中

def new
  ...
  @user_profile = @user.user_profiles.new
end

应该是这样的

最新更新