5

This is what I have in my erb.js file....but it doesn't work:

  1 //Update with a message
  2 $('#follow-update').html("<%= follow_button(@question) %>")

follow_button is a helper:

20   def follow_button(resource)
 21     
 22     type = resource.class.name
 23     follow_status = current_user.following?(resource)
 24 
 25     verb = "Follow" if follow_status == false
 26     verb = "Unfollow" if follow_status == true
 27 
 28     content_tag(:div, :class => "follow-button") do
 29       link_to "#{verb} this #{type} ", follow_path(:followed_type => type,
 30                                                   :followed_id => resource.id,
 31                                                   :follow_verb => verb), 
 32                                                   :class => "button",
 33                                                   :remote => true
 34     end
 35   end
 36 end

The helper stand-alone works fine, but I want it to update my button. Perhaps there's a way to just update the text without replacing the whole helper?

Satchel
  • 16,414
  • 23
  • 106
  • 192
  • hmm...okay I played around with just changing the button text, so far so good...may need to delete this.... :) – Satchel Apr 30 '11 at 04:57
  • nope, I do need it to redisplay the helper because the logic needs to run again.... – Satchel Apr 30 '11 at 05:01

4 Answers4

4

Create a partial that holds your contains only your helper.

For example: '/wherever/_follow_button.html.erb'

Inside, call your helper:

<%= follow_button(question) %>

Next, render it using JS.

$('#some-id').html("<%= escape_javascript(render('/wherever/follow_button', :question => @question)) %>");

There are ways to make this more efficient but hopefully this helps for now.

mikeborgh
  • 1,192
  • 11
  • 22
0

You can't call a helper method from a js.erb file unless you explicitly include it as described in Using a Rails helper method within a javascript asset . For example:

<% environment.context_class.instance_eval { include ApplicationHelper } %>

And you should be careful about escaping your HTML too.

Community
  • 1
  • 1
Leopd
  • 41,333
  • 31
  • 129
  • 167
0

You will need escape_javascript

$('#follow-update').html("<%= raw( escape_javascript( follow_button(@question ))) %>");

If this doesn't work, please see show the returned ajax text and the button html

natedavisolds
  • 4,305
  • 1
  • 20
  • 25
-1

Sorry, I cannot test right now, but have you paid attention to html safe or javascript escapes?

e.g. try to enclose your follow_button(@question)in raw() or escape_javascript()?

user229044
  • 232,980
  • 40
  • 330
  • 338
Pierre
  • 8,368
  • 4
  • 34
  • 50