1

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

4
  • Have you ever tried Gon gem? github.com/gazay/gon Commented Jan 3, 2023 at 4:33
  • @SivaGanesh gem of choice when you absolutely want to make a godaweful mess of the front and back end of your application. Separating concerns is boring. Commented Jan 3, 2023 at 13:58
  • Thank you for your suggestion @SivaGanesh, in any time I see the gem. Commented Jan 3, 2023 at 16:36
  • @max lmao hahah Commented Jan 3, 2023 at 16:37

1 Answer 1

4

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.

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

2 Comments

Hello, @Rein you are right. I wanted to consult it for a practice but it is better to separate the priorities. Thanks for your time. Anyway making request $.ajax worked for me
@SamuelD. Welcome. Yes ajax (XHR) is one way to fix it. Good luck on your project.

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.