Ruby on rails 路由作为命名空间的 Crud

Ruby on rails Crud for routes as namespaces

我正在尝试在 rails 中创建 crud。我认为我在命名空间中的路由运行不正常。当我尝试创建新记录(国家/地区)时,当请求应该在 POST /admin/countries

上执行创建操作时,它会将我重定向到索引操作

代码如下:

控制器:

class Admin::CountriesController < ApplicationController

    layout "admin"


  def index

    @countries = Country.all

  end

  def show
    @country = Country.find(params[:id])
  end

  def new
    @country = Country.new
  end

  def edit
    @country = Country.find(params[:id])
  end

  def create
    abort("Message goes here")
    @country = Country.new(country_params)
    if @country.save
        redirect_to @country
    else
        render 'new'
    end

  end

  def update
    @country = Country.find(params[:id])

    if @country.update(country_params)
        redirect_to @country
    else
        render 'edit'
    end

  end

  def destroy
        @country = Country.find(params[:id])
        @country.destroy

        redirect_to countries_path      
  end

  private
    def country_params
        params.require(:country).permit(:name, :status)
    end

end

动作视图(新)

<%= form_for [:admin, @country] do |f| %>
                  <div class="box-body">
                    <div class="form-group">
                      <%= f.label :name %>
                      <%= f.text_field :name, :class => 'form-control', :placeholder => 'Country name' %>
                    </div>
                    <div class="checkbox">
                      <label>
                        <%= f.check_box :status %> Is enabled?
                      </label>
                    </div>
                  </div><!-- /.box-body -->

                  <div class="box-footer">
                    <%= f.submit :class => "btn btn-primary" %>
                  </div>
                <% end %>

路线

Rails.application.routes.draw do


  root "auth#login"

  get 'shop', :to => "auth#index"

  match ':controller(/:action(/:id))', :via => [:get,:post]
  match ':controller(/:action(/:id))', :via => [:get,:post], controller: /admin\/[^\/]+/

  namespace :admin do
   # root "auth#login"

    resources :countries
  end

end

namespaceresource 路线移至匹配线上方。这两条 match 行匹配所有路由,因此您的资源路由永远不会被使用。

您的路线文件应如下所示:

Rails.application.routes.draw do
  root "auth#login"

  get 'shop', :to => "auth#index"

  namespace :admin do
    resources :countries
  end

  match ':controller(/:action(/:id))', :via => [:get,:post]
  match ':controller(/:action(/:id))', :via => [:get,:post], controller: /admin\/[^\/]+/

end