Hacking RJS behaviour in Rails 5
Asked Answered
R

2

10

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?

Rind answered 16/8, 2017 at 2:26 Comment(5)
So you mean you cant use rjs in rails 5?Athene
@AkiraSuzuki Yeah I believe it was taken out in rails 3.xRind
You can still respond to js and have it update your view in rails 5.2 new_user.js.erb see: edgeguides.rubyonrails.org/…Cullis
@RGB but RJS is deprecated?Rind
its not RJS anymore, but the 'behaviour' is still available. see the Edge guideCullis
R
1

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.

Rind answered 23/8, 2017 at 0:4 Comment(0)
J
2

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
Juniejunieta answered 22/8, 2017 at 12:59 Comment(0)
R
1

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.

Rind answered 23/8, 2017 at 0:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.