【问题标题】:Accessing a method in rails controller via button/link通过按钮/链接访问 Rails 控制器中的方法
【发布时间】:2014-03-25 13:17:48
【问题描述】:

我试图按照这个线程上的解决方案 - Rails 3 link or button that executes action in controller

我在 routes.rb 文件中定义了 :update_question:

  resources :surveys do
    put :update_question, :on => :member
  end

在我的控制器中:

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]
  before_action :set_question

  # GET /surveys
  # GET /surveys.json
  def index
    @surveys = Survey.all
  end

  # GET /surveys/1
  # GET /surveys/1.json
  def show
  end

  def survey
    @survey = Survey.find(params[:survey_id])
  end

  # GET /surveys/new
  def new
    @survey = Survey.new
  end

  # GET /surveys/1/edit
  def edit
  end

  def update_question
    flash[:alert] = "getting there man"
  end

并在 html 中列出了此处的链接:

<%= link_to "Next Question", update_question_survey_path(@survey), {:method => :put} %>

但是当我点击链接时,我得到了这个错误:

Template is missing
Missing template surveys/update_question, application/update_question with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}.

这似乎逃避了它正在寻找一个视图 - 但实际上我只是希望它在我的调查控制器中运行该方法并更新正在显示的问题。也许我的做法是错误的,非常感谢任何帮助/建议!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    那是因为正确地到达了动作,但是 Rails 尝试渲染一些东西。默认情况下,它将查找与操作同名的视图文件。

    你应该这样做:

    def update_question
      set_survey
      # do stuff
      flash[:alert] = "getting there man"
      redirect_to survey_path(@survey)
    end
    

    【讨论】:

    • 啊,这完全有道理 - 我可以设置我的新参数来显示新问题。
    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多