【问题标题】:NoMethodError in UsersController#new (undefined method `userprofiles' for #<User:0x000000059c50e0>) [closed]UsersController#new 中的 NoMethodError(#<User:0x000000059c50e0> 的未定义方法“userprofiles”)[关闭]
【发布时间】:2014-12-16 13:49:56
【问题描述】:

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

错误:

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

型号

  • user.rb (belongs_to :userprofile)
  • user_profile.rb (belongs_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

【问题讨论】:

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


    【解决方案1】:

    用户模型

     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
    

    应该是这样的

    【讨论】:

    • 谢谢您的回复先生(它有效),但是如果 1 对 1 关系呢? has_one :user_profile in User(model) and belongs_to :user in UserProfile(model) .. 我试过了,但没用。
    • 那么你可以使用@user.build_user_profile
    • 先生,非常感谢您的回复(确实有效)。我第一次遇到“构建”这个词,但我会搜索它。抱歉,我是 Rails 新手。你的回答真的对我有很大帮助。我希望每次遇到 Rails 问题时都能 ping 通你。谢谢! :)
    • 当然...请阅读 Rails 指南
    • 顺便问一下,先生,我在哪里可以 ping 通您?我可以拥有你的 gmail 帐户吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多