Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hacking RJS behaviour in Rails 5

I have a old rails 2.x project that I have converted mostly over to rails 5.

One issue is some of my actions used RJS, so it looked like:

if request.xhr?
  render :action => 'new_user' and return
end

The new_user.js.rjs looks something like:

page.call "User.create", render(:partial => 'new_user'), {:userId => @user.id}

Looking at the response in chrome I can see it is just returning:

User.create('<tr><td>....</td></tr>', {"userId" : 123});

I only have to support the page.call type RJS call, what would be a easy "hack" to get this to work in rails 5?

I don't want to modify all of my javascript code, I just need to basically have a javascript block that I pass the JS code to in my view pages right?

like image 553
Blankman Avatar asked Aug 16 '17 02:08

Blankman


2 Answers

Try to render a response as a string:

if request.xhr?
  render render_to_string partial: 'new_user',
    locals: { userId: @user.id },
    layout: false
end

Or try to use format handler instead:

respond_to do |format|
   format.rjs do
     render render_to_string partial: 'new_user',
       locals: { userId: @user.id },
       layout: false
   end
end
like image 176
itsnikolay Avatar answered Sep 16 '22 14:09

itsnikolay


I ended up returning a JSON response to my view pages like this:

some_partial_html = render_to_string(:partial => 'something')

response = {
  "html": some_partial_html,
  "a" : 1
}.to_json
render json: response

And then in my view I used the json response values as arguements to the javascript object that performs the functionality I needed.

like image 32
Blankman Avatar answered Sep 19 '22 14:09

Blankman