0

I'm trying to refactor some legacy code at the moment. It currently goes something like this:

Controller

def create
  # do stuff

  respond_to do |format|
    format.html { do stuff }
    format.js { render partial: 'stage_two', locals: { some instance variables } }
  end
end

Then in the views/controller_name/_stage_two.js.erb there is:

$('.some_element').children().fadeOut( function() {
  $('.some_element').children().remove();
  $('.some_element').html("<%=j render partial: 'form', locals: { stuff } %>");
  $('.some_element .stage_two').fadeIn();
});

So basically the controller action is essentially rendering javascript. And that particular javascript is just removing an element from the page, changing the contents, then fading it back in. Is there a better way to do this? I know typically javascript lies in the app/assets/javascripts.

2 Answers 2

1

Your current implementation is quite DRY already and standard way.

The html request should also render the same partial but with layout.

The js request should render js response(rendering partial) and update the portion of page.

I know typically javascript lies in the app/assets/javascripts.

Those are your assets, this stage_two.js.erb is not essentialy your assets file, this is instead your action handling for the js response.

Definitely for smaller update actions you can use json request and receive json response to update view, but for many of the cases(esp. when dealing with large data) that fails, and your current implementation is fine in that...

Sign up to request clarification or add additional context in comments.

6 Comments

What if I wanted to use HAML? Then it wouldn't be possible to use coffeescript as I was hoping for? I'd like to get away from plain js/jQuery and use coffeescript. :)
you can still have _stage_two.coffee.erb and follow coffeescript syntax for same...
You can make partials in the assets\javascripts directory? Does Rails first look in views, then boil down to the assets?
But these aren't assets.. This is dynamic js content being executed.... If you feel need to DRY this up.. create a js function update_my_content() and call update_my_function("<%=j render partial: 'form', locals: { stuff } %>") from .js.erb file...
Oh, I think I see what you're saying. I really appreciate the help. :)
|
0

Typically, the usual way to do this is to have the controller return JSON (I'd have it render a formated version of the variables), and then to have the JS do a normal AJAX call and update the element with the JSON data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.