Home > Net >  in Rails, How to make a query in javascript?
in Rails, How to make a query in javascript?

Time:01-04

Given the id of an element I need to make a query in javascript, for example:

javascript:
  var post_value = $(".post").val() # return a post ID;
  var post = #{Post.find_by(id: post_value).to_json.html_safe};

But the post_value variable don't recognize it

If I manually pass a value to it, it recognizes it and asks me the query of the post, for example:

  var post = #{Post.find_by(id: 181).to_json.html_safe}; # If work because I pass 181 as an ID value

I would be very grateful if you could help me

CodePudding user response:

This line gets rendered in server side. It will not have any access to the browser's runtime context. As this gets executed before reaching the user.

  var post = #{Post.find_by(id: post_value).to_json.html_safe};

Either use XHR (have another endpoint API purely for data objects like json) or query your Post object/s in controller, pass the object to the view and render the Post object inside the view. It is also a bad practice to have DB queries inside the view template files.

It's also weird to use javascript to render elements in the backend context. You generally use javascript with the context or assumption that it is to be executed in the user's side, separated with the backend context.

  • Related