简体   繁体   中英

Rails - Render html with an ajax request in controller

I would like render format.html if param[:date] != nil and render .js if it's not nil.

My link_to :

<%= link_to place_path(place, date: params[:date]), id: "#{place.id}", remote: true, authenticity_token: true, data: { title: place.city }, target: "_blank" do %>

My controller :

class PlacesController < ApplicationController    
  def show
    if params[:date] == nil
      respond_to do |format|
        format.html {
          preparation_of_instance_variables_for_show_view
        }
        format.js { }
      end
    else
      respond_to do |format|
        format.html {
          preparation_of_instance_variables_for_show_view
        }
        format.js {
          render format: 'html' # <= where I want to render format.html
        }
      end
      go_to_show_view
    end


  end

  private

  def preparation_of_instance_variables_for_show_view
    @place = Place.find_by_id(params[:id])
    if params[:date].present?
      @guests = Booking.accepted.where(place: @place, date: Date.parse(params[:date])).map(&:guest)
    end
  end

How I can to redirect to the format.html just for this case?

You say in your question that you want to render html if its != (not equal) to nil and to render js if it's not equal to nil. You can't render both on the same condition! Either way you should wrap the respond_to around the if condition:

def show
  respond_to do |format|
    if params[:date] # This means if params[:date] has a value (true)          
      format.html {
        preparation_of_instance_variables_for_show_view
      }
    else # If params[:date] is equal to nil 
      format.js {}
    end # End of if params[:date]
      go_to_show_view
  end # End of respond_to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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