【问题标题】:Ruby on rails Crud for routes as namespacesRuby on rails Crud 作为命名空间的路由
【发布时间】:2015-04-29 19:56:07
【问题描述】:

我正在尝试在 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

【问题讨论】:

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


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-09
      • 2015-05-15
      • 2021-02-18
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多