Skip to content

Instantly share code, notes, and snippets.

@mnishiguchi
Last active February 15, 2018 01:51
Show Gist options
  • Save mnishiguchi/f01fe5144e6840d1906c6266da1d1347 to your computer and use it in GitHub Desktop.
Save mnishiguchi/f01fe5144e6840d1906c6266da1d1347 to your computer and use it in GitHub Desktop.
Rails - redirect - friendly forwarding

Rails - redirect - friendly forwarding

A: Using session

B: Using querystring

QuestionsController

class QuestionsController < ApplicationController
  # ...

  # GET questions/:id/edit
  def edit
    @question = Question.find(params[:id])
    @redirect_url = redirect_url
  end

  # PATCH questions/:id
  def update
    @question = Question.find(params[:id])
    @question.answer = params[:question][:answer]
    if @question.save
      flash[:success] = "Answer was successfully saved"
      redirect_to redirect_url
    else
      @redirect_url = redirect_url
      render :edit
    end
  end

  # ...

  private

  def redirect_url
    params[:redirect_url].presence || pulse_questions_url
  end

  #...
end

Links to Question form from another model Property

    1. Store current url to a variable redirect_url
    1. Pass redirect_url to link urls as querystring
- redirect_url = property_url(@property)
.panel
  .panel-heading
    h4.panel-title
      | Questions

  .panel-collapse
    .panel-body
      .form-wrapper
        h3 Questions
        table
          thead
            tr
              th Questioner
              th Question
              th Answer
          tbody
            - @questions.each do |question|
              tr
                td
                  = Mail::Address.new("#{question.questioner_name} <#{question.questioner_email}>").to_s
                  br
                  | #{time_ago_in_words(question.created_at)} ago
                td
                  = question.question
                td
                  - if question.answered?
                    = question.answer
                  - elsif question.answer.present?
                    a[href="#{edit_question_path(question, redirect_url: redirect_url)}"]
                      = question.answer
                  - else
                    a.btn.btn-sm.btn-primary[
                      href="#{edit_question_path(question, redirect_url: redirect_url)}"
                      | Answer

Question edit form

  • Include redirect_url in a form as a hidden field so that we can retain redirect_url on re-rendering.
= content_for :page_header do
  h1 Answer
  
  = simple_form_for @question do |f|
    = hidden_field_tag :redirect_url, @redirect_url

    = f.input :answer, as: :text, label: "Answer"
    div
      = link_to "Back", @redirect_url, class: "btn btn-default btn-sm"
      = f.button(:submit, "Answer question", class: "btn btn-primary btn-sm")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment