flyingarmadillo
flyingarmadillo

Reputation: 2139

pass two instance variables to js.erb files?

I need to pass two instance variables to a javascript file that is being used by an ajax request to update a user display. This is what I need to do:

respond_to do |format|
    if @post.save
        format.js { @post @user_vote }  # <-- right here
    else 
        format.html { redirect_to :back, :alert => 'There was an error in removing the vote' }
    end
end 

How is this done?

Upvotes: 2

Views: 3747

Answers (2)

pdpMathi
pdpMathi

Reputation: 775

There is no need to pass the instance variables if you use js.erb files. You can directly put the rails tag and access those variables inside the js.erb file

Eg:

In your controller just put

format.js #instead of format.js { @post @user_vote }

and in js.erb file you can access the instance variable as

$('#ele').html("<%= @post.name %>");

Upvotes: 7

jstr
jstr

Reputation: 1281

The instance variables in your ActionController action are available in your views automagically. E.g. your controller:

# posts_controller.rb
def update

  # Your implementation here
  @post = ...
  @user_vote = ...

  respond_to do |format|
    if @post.save
      format.js
      format.html { redirect_to post_path(@post) }
    else
      format.js { ... }
      format.html { redirect_to :back, ... }
    end
  end
end

Then in your update.js.erb:

# update.js.erb
console.log('Post: <%= @post.inspect %>');
console.log('User vote: <%= @user_vote %>');

# Your JS implementation here

(Also I noticed your logic in the respond_to block is probably going to cause problems. You should render both js and html formats for both success and failure conditions of @post.save.)

Upvotes: 2

Related Questions