简体   繁体   English

Rails中的自定义方法路线

[英]Custom Method Route in Rails

I've seen this question asked all over the place, but for seemingly no reason at all, I can't figure out how to Route a custom method in rails. 我已经到处问过这个问题,但是似乎根本没有理由,我不知道如何在rails中路由自定义方法。

Quick Overview: I built a small application and generated a scaffold called answers. 快速概述:我构建了一个小型应用程序,并生成了一个名为Answers的支架。 When I generated the scaffold, it automatically got its answers_controller.rb in the controller folder and its answers folder in the views. 当我生成支架时,它会自动在controller文件夹中获得answers_controller.rb并在视图中获得Answers文件夹。

In the answers_controller, i added one custom method called random. 在Answers_controller中,我添加了一种称为random的自定义方法。 The entirety of answers_controller is below: 整个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

end 结束

in my views/answers folder I made a folder called random.html.erb, which only contains an html h1 tag. 在我的views / answers文件夹中,我创建了一个名为random.html.erb的文件夹,其中仅包含html h1标签。 In my routes file, I have the following: 在我的路线文件中,我具有以下内容:

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

Every resource on the internet says this is the way to do it, but when i run localhost:3000/random I just get a routing error. 互联网上的每个资源都说这是做到这一点的方法,但是当我运行localhost:3000 / random时,我只会遇到路由错误。 I'm including a picture of the file structure, but for the life of me, I have no idea why this doesn't work. 我包括了文件结构的图片,但是对于我自己的一生,我不知道为什么这不起作用。

在此处输入图片说明

Your routes mean that this random action will be accessible via /answers/random path. 您的路线意味着可以通过/answers/random路径访问此random操作。 Plus your resources :answers line (the one without block) should be removed. 加上您的resources :answers行( resources :answers那一行)应被删除。
You may find more info in Rails Guides . 您可以在《 Rails指南》中找到更多信息。

另一种方法是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM