铁轨的漂亮网址

时间:2014-06-16 21:49:19

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

我试图让它发挥作用。这是我现在的佣金路线:

groups GET    /groups(.:format)                           groups#index
                         POST   /groups(.:format)                           groups#create
               new_group GET    /groups/new(.:format)                       groups#new
              edit_group GET    /groups/:id/edit(.:format)                  groups#edit
                   group GET    /groups/:id(.:format)                       groups#show
                         PATCH  /groups/:id(.:format)                       groups#update
                         PUT    /groups/:id(.:format)                       groups#update
                         DELETE /groups/:id(.:format)                       groups#destroy

我想要做的是删除"群组"从链接添加slug而不是id。 这是我的控制器:

class GroupsController < ApplicationController
  before_action :find_group, only: [:show]
  after_action :assign_slug, only: [:create, :update]

  def index
    @groups = Group.all
  end

  def show
  end

  def new
    @group = Group.new
  end

  def create
    @group = Group.new(group_params)
    if @group.save
      flash.notice = "Group has been successfully created!"
      redirect_to @group
      binding.pry
    else
      flash.alert = "oops!"
      redirect_to action: :new
    end
  end

  private
    def group_params
      params.require(:group).permit(:title, :description, :country, :city, :category_id)
    end

    def find_group
      @group = Group.find_by_slug(params[:slug])
    end

    def assign_slug
      @group.update(slug: @group.title.parameterize)
    end

end

我如何让它发挥作用?感谢:。)

1 个答案:

答案 0 :(得分:0)

如果这是你想要的:

routes.rb

get ':slug', to: 'pages#show', as: :groups_show
put ':slug', to: 'pages#update', as: :groups_update
delete ':slug', to: 'pages#destroy', as: :groups_delete

通过这种方式,slug将作为参数被捕获并发送给控制器。