Rails - 在控制器

时间:2017-04-03 14:05:24

标签: javascript jquery ruby-on-rails ajax controller

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

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

1 个答案:

答案 0 :(得分:0)

你在问题​​中说你要渲染html,如果它的!=(不等于)为nil,并且如果js不等于nil则渲染js。你不能在同样的条件下渲染它们!无论哪种方式,你都应该围绕if条件包装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