将控制器存储在子文件夹中时,名称错误unitititalized constant

时间:2016-04-26 12:18:13

标签: ruby-on-rails controller namespaces

我正在构建的JSON API在命名空间API和V1下有一组路由(所有路由都以API / V1开头。 我现在正在创建一组新的控制器和模型,这些控制器和模型都链接到“关联”的“概念”,所以我决定将它们存储在我的文件夹“controllers”和“models”中的子文件夹“association”中。我还为相对于这些控制器的路由创建了一个新的命名空间“关联”。

我一直在试图在OfficesController的创建动作上发布POST,但我得到了这个:

Started POST "/api/v1/association/account_assos/1/offices" for ::1 at 2016-04-26 13:54:00 +0200
Processing by Api::V1::Association::OfficesController#create as JSON
  Parameters: {"office"=>{"name"=>"Samu Paris", "contact_mail"=>"samuparis@gmail.com", "contact_phone"=>"+33666027414", "address"=>"148 BD BINEAU", "city"=>"PARIS", "postcode"=>"92200", "photos_attributes"=>[{"image_url"=>""}]}, "account_asso_id"=>"1"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["email", "mariashi@gmail.com"]]
Completed 500 Internal Server Error in 50ms (ActiveRecord: 1.0ms)

**NameError - uninitialized constant Api::V1::Association::OfficesController::Association:**

我的路线如下:

namespace :api, defaults: { format: :json } do
      namespace :v1 do
        namespace :association do
          resources :account_assos, only: [ :index, :show, :update, :create ] do
            resources :offices, only: [ :index, :show, :create ]
          end
        end
      end
    end

有问题的控制器:

class Api::V1::Association::OfficesController < Api::V1::BaseController
  before_action :set_office, only: [ :show, :update, :destroy]
  before_action :set_account_asso, only: [:create, :index]


  def index
    # is this the best way ??
    if (current_user.created_account_asso == @account_asso) || ((current_user.account_asso == @account_asso) && (current_user.status == "manager"))
      @offices = policy_scope(office).where(account_asso: @account_asso)
      render :index
    else
      render json: {message: "Unauthorized"}
    end
  end

  def show
    authorize @office
  end

  def update
    authorize @office
    if @Office.update(office_params)
      render :show
    else
      render_error
    end
  end

  # input account
  def create
    @office = @account_asso.offices.build(office_params)
    authorize @office
    if @office.save
      render :show
    else
      render_error
    end
  end

  def destroy
    authorize @office
    if @office.destroy
      render json: {success: "Office successfully destroyed"}
    else
      render json: {error: "There was an error please try again"}
    end
  end

  private

  def set_account_asso
    @account_asso = Association::AccountAsso.find(params[:account_asso_id])
  end

  def set_office
    @office = Office.find(params[:id])
  end

  def Office_params
    params.require(:office).permit( :name,
                                    :address,
                                    :contact_mail,
                                    :contact_phone,
                                    :address,
                                    :city,
                                    :postcode,
                                    photos_attributes: [ :image_url ]
                                  )
  end

  def render_error
    render json: { errors: @office.errors.full_messages }, status: :unprocessable_entity
  end

end

offices_controller存储在api / v1 / association中,这对我来说似乎是一致的。为什么我会得到

  **NameError - uninitialized constant Api::V1::Association::OfficesController::Association:** 

我的模型相对于“关联”概念存储在模型/关联中。这是我的AccountAsso模型,例如(models / association / account_asso.rb):

class Association::AccountAsso < ActiveRecord::Base

  # associations
  has_many :users, dependent: :destroy
  has_many :offices, dependent: :destroy
  belongs_to :admin, class_name: "User", foreign_key: "admin_user_id"


  # validations

  validates :name, presence: true, length: {minimum: 2}
  validates_format_of :contact_mail,:with => Devise::email_regexp
  validates :contact_tel, format: {
      with:     /\A(\+33)[1-9]([-. ]?[0-9]{2}){4}\z/,
      message:  'Le format de votre numéro doit être du type +33602385414'
    }
  validates :iban, presence: true, format: {
      with:     /\A[a-zA-Z]{2}\d{2}\s*(\w{4}\s*){2,7}\w{1,4}\s*\z/,
      message:  'Le format de votre IBAN doit être du type FR70 3000 2005 5000 0015 7845 Z02'
    }, allow_blank: true

  validates :bic, presence: true, format: {
      with:     /([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)/,
      message:  'Le format de votre BIC doit être du type AXABFRPP  '
    }, allow_blank: true

  validates :admin, presence: true, uniqueness: true


  # validates :legal_status, presence: true,

end

3 个答案:

答案 0 :(得分:0)

由于在该路径上控制器无法找到父常量Association,因此请使用Api::V1::Association的完整路径或相对的一个类方法::parent

@account_asso = Api::V1::Association::AccountAsso.find(params[:account_asso_id])

@account_asso = parent::AccountAsso.find(params[:account_asso_id])

好吧,因为AccountAsso是一个模型,它的声明应该从命名空间根来计算,因为它们不是rails服务子系统等的一部分。当然你可以有子模型,但它们应该属于父模型而不是另一个,所以:

应用/模型/ account_asso.rb

class AccountAsso < ActiveRecord::Base ;end

和子模型:

应用/模型/ account_asso / new_asso.rb

class AccountAsso::NewAsso < AccountAsso ;end

或:

应用/模型/ account_asso / otherm.rb

class AccountAsso::Otherm < ActiveRecord::Base ;end

注意:模型名称必须是模型文件的相应路径,否则rails无法正确接收。

答案 1 :(得分:-1)

Started POST "/api/v1/association/account_assos/1/offices" for ::1 at 2016-04-26 13:54:00 +0200
Processing by Api::V1::Association::OfficesController#create as JSON
  Parameters: {"office"=>{"name"=>"Samu Paris", "contact_mail"=>"samuparis@gmail.com", "contact_phone"=>"+33666027414", "address"=>"148 BD BINEAU", "city"=>"PARIS", "postcode"=>"92200", "photos_attributes"=>[{"image_url"=>""}]}, "account_asso_id"=>"1"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["email", "mariashi@gmail.com"]]
Completed 500 Internal Server Error in 50ms (ActiveRecord: 1.0ms)

**NameError - uninitialized constant Api::V1::Association::OfficesController::Association:**

查看URL,它的名称也是错误的,而不是办公室,而不是办公室。

答案 2 :(得分:-1)

你重启了服务器吗?此外,您的association文件夹应位于以下路径:app/controllers/api/v1/association/