1

I'm developing web app using Ruby on Rails 7.0. I tried to use data from DB created by rails in JS, but I got a error. I'm a beginner, especially when it comes to backend. I hope someone's help :)

<p style="color: green"><%= notice %></p>

<h1>Contents</h1>

<div id="contents" data-contents="<%= @contents.to_json %>"></div> 

<script>
var contentsHash = $('#contents').data('contents');
console.log(contentsHash[0].title);
</script>
  • application.html.erb
<!DOCTYPE html>
<html class="h-100">
  <head>
    <title>MapTest</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <%= javascript_importmap_tags %>
    <script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
  </head>

  <body>
  ...
  </body>
</html>

I tried to access data by getting attributes of div tag(id="contents").

2
  • welcome to stack overflow. Please, do not link images of your code, refer to the question guidelines here: stackoverflow.com/help/how-to-ask. Commented Jun 13, 2023 at 3:36
  • 1
    you will observe that the javascript variable contentsHash contains a string. So of course contentsHash[0].title will fail. You need to JSON.parse(contentsHash) Commented Jun 13, 2023 at 3:38

2 Answers 2

1

For large sets of data, from a rails view to javascript, i use the gem Gon.

https://github.com/gazay/gon

It exists others solutions Rails 4: Passing variables to javascript

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

Comments

0

Perhaps do away with the DIV entirely, changing your index.html file to be:

<p style="color: green"><%= notice %></p>

<h1>Contents</h1>

<script>
var contentsHash = <%= @contents.to_json.html_safe %>;
console.log(contentsHash[0].title);
</script>

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.