簡體   English   中英

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

[英]Rails - Render html with an ajax request in controller

如果param [:date]!= nil我想渲染format.html,如果不是nil我想渲染.js。

我的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 %>

我的控制器:

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

在這種情況下,如何才能重定向到format.html?

您在問題中說,如果HTML的!=(不等於)為nil,則要呈現html;如果不等於nil,則為js。 您不能在相同條件下渲染兩者! 無論哪種方式,您都應該在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