Error using erb in js.coffee files in the rails as

2019-02-25 14:49发布

问题:

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?

回答1:

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"))