【发布时间】: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