Rails错误“未初始化的常量User :: Corporateprofiles”

时间:2016-01-29 12:43:37

标签: ruby-on-rails ruby

我正在尝试创建一个程序,在该程序中创建用户时,会自动创建一个corporateprofile。但是,在尝试查看公司资料时,我一直遇到以下错误..

CorporateprofilesController中的NameError#show

uninitialized constant User::Corporateprofiles

我已经一遍又一遍地阅读我的代码以查找拼写错误,但无效,请注意我使用的是每个用户在corporateprofile上的嵌套路由。

的routes.rb

Myapp::Application.routes.draw do
  resources :users do
    resources :searches
    resources :corporateprofiles
  end
end

Corporateprofiles Controller

class CorporateprofilesController < ApplicationController
  before_action :require_user

  def show
    @corporateprofile = current_user.corporateprofiles.find(params[:id])
  end

  def edit
    @corporateprofile = current_user.corporateprofiles.find(params[:id])
  end

  def update
    @corporateprofile = Corporateprofile.find(current_user.corporateprofile.id)
    if @corporateprofile.update_attributes(corporateprofile_params)
      flash[:success] = "Profile Updated"
      redirect_to current_user
    else
      flash.now[:error] = "Something went wrong" 
      render edit_user_corporateprofiles_path
    end
  end

  private

  def profile_params
    params.require(:corporateprofile).permit(:companyname, :companylogo,:companybanner,:companywebsite,:companyindustry,:companytype, :companyheadquarters,:companysize,:companyvideo,:aboutus,:city,:state,:country)
  end
end

公司简介模型

class Corporateprofile < ActiveRecord::Base
 belongs_to :user
end

用户模型

class User < ActiveRecord::Base
  after_create :build_profile

  has_many :searches, dependent: :destroy
  has_one :corporateprofiles, dependent: :destroy

  def build_profile
    Corporateprofile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly.
  end

  has_secure_password 
end

已经阅读了所有类似的堆栈溢出帖子,即使是错误检查但是我仍然无法弄清楚导致错误的是什么。

任何帮助都会非常感激

2 个答案:

答案 0 :(得分:1)

您有错误,因为您破坏了rails命名约定。因此,对于表名corporate_profiles

  • 模型文件名应为corporate_profile.rb
  • 模型类名称应为CorporateProfile
  • 控制器类名称应为CorporateProfilesController
  • has_one关联名称应为corporate_profile

答案 1 :(得分:-1)

您收到此错误是因为您设置了has_one :corporateprofiles。您使用了多个模型名称,但rails需要单数。因此,它正在寻找班级Corporateprofiles

首先 - 要解决此问题,请更改命名

将类命名为CamelCase是惯例 - 所以将模型更改为CorporateProfile。您还必须将文件更改为 corporate_profile(_controller).rb

这也使您的关系更容易阅读和写作。

class User
  has_one :corporate_profile, dependent: :destroy
  # ... other stuff
end

其次 - 我建议您改进after_create 回调。我觉得直接访问self比调用其他模型和定义user: self

要好得多
def build_profile
  self.corporate_profile = CorporateProfile.create
end