2

I have the following code:

/assets/javascripts/home.js.coffee.erb

jQuery ->
  addClickListeners = ->
        $(document).on 'click', '#add-chord-link', addChord
        $(document).on 'click', '#remove-chord-link', removeChord

    addChord = (e) ->
        e.preventDefault()
        console.log("<%= asset_path('rails.png') %>")
        console.log("<%= link_to 'Sign up now!', '#' %>")
        console.log('addChord clicked')
        $('#chord-choices').append('addedChord')

    removeChord = (e) ->
        e.preventDefault()
        $('#chord-choices select').last().remove()
        console.log('removeChord clicked')

    addClickListeners()

The console output for the console.log("<%= asset_path('rails.png') %>") is /assets/rails.png, which is what I expect. However, whenever I include console.log("<%= link_to 'Sign up now!', '#' %>") I get an error when the page is loaded stating:

    undefined method `link_to' for #<#<Class:0x007f9095960938>:0x007f9095b78ab8>

Why is this not working?

jackerman09
  • 2,492
  • 5
  • 29
  • 46

1 Answers1

4

The problem

The reason is Sprockets, the gem behind Assets pineline, doesn't depend on Rails to process erb. See the native helpers available https://github.com/sstephenson/sprockets#invoking-ruby-with-erb

Rails added some more helpers to Assets Pineline in ActiveSupport, they are all you can use. You can find them here: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html

link_to is a helper belonging to ActionView, so it's not included in Assets Pineline.

The hacks

There are some solutions to allow your using ActionView helpers within Assets Pineline:

Route helpers in asset pipeline

https://github.com/sstephenson/sprockets/issues/218

How to include ActionView helpers in the assets pipeline?

My suggestions

If all you need is the link in question or a little bit more, no need the trouble to hack around. Use plain text or a Javascript helper. That's enough.

//plain text
"<a href='#'>Sign up</a>"

//JS helper
Link = {}
Link.sign_up = "<a href='#'>Sign up</a>"
Link.link_to = (url, anchor) ->
  "<a href=\"#{url}\">#{anchor}</a>" 

console.log(Link.sign_up)
console.log(Link.link_to("#", "Sign up"))
Community
  • 1
  • 1
Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • Thanks! I actually need something a little more complicated than the link_to, but I was getting the same error with both so I used link_to in the example because it was simpler. I need to use the collection_select helper, which is populated from the model, any suggestion for doing this? Thanks again – jackerman09 Nov 08 '13 at 01:39
  • 1
    It seems you are going to mix some data in assets, I personally don't like that practice. I suggest you to consider using Ajax to pull js or JSON instead. – Billy Chan Nov 08 '13 at 01:44
  • 1
    Different from assets, in JS repsones, you can use any helpers in js.erb from app/views – Billy Chan Nov 08 '13 at 01:45