简体   繁体   English

Rails-在控制器中使用Ajax请求渲染HTML

[英]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. 如果param [:date]!= nil我想渲染format.html,如果不是nil我想渲染.js。

My link_to : 我的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? 在这种情况下,如何才能重定向到format.html?

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. 您在问题中说,如果HTML的!=(不等于)为nil,则要呈现html;如果不等于nil,则为js。 You can't render both on the same condition! 您不能在相同条件下渲染两者! Either way you should wrap the respond_to around the if condition: 无论哪种方式,您都应该在if条件周围包裹response_to:

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

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

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