Rails: access controller instance variable in CoffeeScript or JavaScript asset file

前端 未结 6 1144
我寻月下人不归
我寻月下人不归 2020-12-01 01:19

In Rails 3.1 it is not possible to access controller instance variables in an asset js.erb or coffee.erb file using syntax such as <%= @foo %>, where @foo is set in the c

6条回答
  •  星月不相逢
    2020-12-01 02:03

    You can edit and add variables to the params array in the controller then access them in the response.js.erb. Here's an example with params[:value]:

    def vote
      value = params[:type] == "up" ? 1 : -1
      params[:value] = value
      @public_comment = PublicComment.find(params[:id])
    
      have_voted = @public_comment.evaluators_for(:pub_votes_up) << @public_comment.evaluators_for(:pub_votes_down)
    
      unless have_voted.include?(@current_user) # vote
        @public_comment.add_or_update_evaluation(:"pub_votes_#{params[:type]}", value, @current_user)
      else                                      # unvote
        @public_comment.delete_evaluation(:"pub_votes_#{params[:type]}", @current_user)
        params[:value] = 0
      end
    
      respond_to do |format|
        format.js # vote.js.erb
      end
    end
    

    And here's an example accompanying response.js.erb

    button = $('<%= ".pub#{params[:type]}_#{params[:id]}" %>')
    label = button.find('strong')
    <% comment = PublicComment.find(params[:id]) %>
    label.html('<%= comment.reputation_for(:"pub_votes_#{params[:type]}").to_i %>')
    
    <% if params[:value] == 1 %>
      button.addClass('btn-success')
    <% elsif params[:value] == -1 %>
      button.addClass('btn-danger')
    <% else %>
      if button.hasClass('btn-success') { button.removeClass('btn-success') }
      if button.hasClass('btn-danger') { button.removeClass('btn-danger') }
    <% end %>
    

提交回复
热议问题