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 :)
error enter image description here enter image description here
index.html.erb
<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").
contentsHashcontains a string. So of coursecontentsHash[0].titlewill fail. You need toJSON.parse(contentsHash)