DVG
DVG

Reputation: 17480

Rails, CoffeeScript and ERB

So I'm messing around witha few javascript responders for a few actions. So, for instance,

def create
  #code omitted
  respond_to do |format|
    if @post.save
      format.html { redirect_to discussion_posts_path(@post.discussion), notice: 'Post was successfully created.' }
      format.js
    else
      format.html { render :action => "new" }
    end
  end
end

#create.js.erb
$("#discussion_posts_table").append("<%= escape_javascript(render(@post)) %>");
$("#post_body").val("");

Now lets say I wanted to convert these javascript functions to Coffeescript (setting aside the fact that it gains almost nothing), if I change the file to create.js.coffee.erb it stops working. What's the proper way to use coffeescript in UJS?

For the record, I have coffee-rails in my Gemfile, and am using coffeescript in the asset pipeline.

Upvotes: 3

Views: 3194

Answers (2)

TheIrishGuy
TheIrishGuy

Reputation: 2573

I've seen .coffee.erb used before. Still looking around for that project.

Ok if they're still in your views, just use .js.coffee

Edit 1: Apparently Rails will still process the erb oddly enough. Edit 2: Also, you can add erb to the end of a js.coffee file, they're jsut preprocessed in a particular order thus that might have thrown off Rails.

Upvotes: 3

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

You need to add the coffee-rails gem to your project for this to work.

Upvotes: 0

Related Questions