2017-04-03 82 views
0

如果param [:date]!= nil,我想渲染format.html,如果不是nil,則渲染.js。Rails - 用控制器中的ajax請求渲染html

我的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只是爲了這個案子?

+0

我有show.js.erb,我使其當我在第一種情況下,但我想渲染show.html.erb對於第二種情況的js要求 –

回答

0

你說在你的問題中,如果你希望呈現html,如果它!!(不等於)爲零,並且呈現js,如果它不等於nil。你不能在相同的條件下渲染兩個!無論哪種方式,你應該換行的respond_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 
+0

對不起,我不是很清楚。 您的解決方案不會呈現給我HTML。另一方面,如果我在檢查器中的link_to上刪除「remote:true」,控制器將顯示我show.html.erb –

+0

是的,這是因爲'remote:true'告訴rails通過AJAX請求該請求期待一個.js響應。也許你可以在你的<%= link_to%>的地方設置if語句,這樣如果有日期,那麼不會顯示'remote:true'(&html),否則如果沒有日期,那麼設置'remote:true' (&js呈現)。 – ThorTL67

+0

當然可以。這是我想到的解決方案。但我認爲這不是很乾淨。 謝謝無論如何;) –