【问题标题】:Custom Method Route in RailsRails 中的自定义方法路由
【发布时间】:2015-01-15 08:26:59
【问题描述】:

我到处都看到过这个问题,但似乎完全没有理由,我无法弄清楚如何在 rails 中路由自定义方法。

快速概述:我构建了一个小型应用程序并生成了一个名为 answers 的脚手架。当我生成脚手架时,它会自动在控制器文件夹中获取它的 answers_controller.rb 并在视图中获取它的 answers 文件夹。

在 answers_controller 中,我添加了一种称为随机的自定义方法。 answers_controller 的全部内容如下:

class AnswersController < ApplicationController
before_action :set_answer, only: [:show, :edit, :update, :destroy]

def index
  @answers = Answer.all
end

def show
end

def random
end

def new
  @answer = Answer.new
end

def edit
end


def create
  @answer = Answer.new(answer_params)

respond_to do |format|
  if @answer.save
    format.html { redirect_to @answer, notice: 'Answer was successfully created.' }
    format.json { render :show, status: :created, location: @answer }
  else
    format.html { render :new }
    format.json { render json: @answer.errors, status: :unprocessable_entity }
  end
end
end

# DELETE /answers/1
# DELETE /answers/1.json
def destroy
@answer.destroy
respond_to do |format|
  format.html { redirect_to answers_url, notice: 'Answer was successfully destroyed.' }
  format.json { head :no_content }
end

结束

在我的视图/答案文件夹中,我创建了一个名为 random.html.erb 的文件夹,其中仅包含一个 html h1 标记。 在我的路线文件中,我有以下内容:

Rails.application.routes.draw do
resources :answers

# this should work, why doesn't it???
resources :answers do
  collection do
    get :random
  end
end

root to: 'dashboard#index'
end

互联网上的每个资源都说这是这样做的方法,但是当我运行 localhost:3000/random 时,我只是得到一个路由错误。我包含了文件结构的图片,但对于我的生活,我不知道为什么这不起作用。

【问题讨论】:

    标签: ruby-on-rails controller routing views


    【解决方案1】:

    您的路线意味着可以通过/answers/random 路径访问此random 操作。加上您的resources :answers 行(没有阻止的行)应该被删除。
    您可以在Rails Guides 找到更多信息。

    【讨论】:

      【解决方案2】:

      另一种方法:

      get '/random/', to: 'answers#random', as: 'random'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-05
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 2019-07-26
        • 1970-01-01
        相关资源
        最近更新 更多