Home > Mobile >  how to combine ruby code with javascript in rails 7
how to combine ruby code with javascript in rails 7

Time:10-28

I need to combine ruby code with javascript, to show something which depends on the server's response.

app/views/posts/index.html.erb

<h1 >Posts</h1>
<div id="posts" data-controller="like" data-like-url-value="<%= like_posts_path %>">
    <div >
        <% @posts.each do |post| %>
            <%= render post %>
        <% end %>
    </div>
</div>
<script>
    if(some condition){
       console.log("All Posts has been loaded successfully.")
    }
</script>

app/controllers/posts_controller.rb

def index
   @posts = Post.all.order(id: :desc)
   if @posts.length > 0
     session[:post] = true
   end
end

I have to use the index action session variable in the index template, I don't have any idea about how to combine ruby code with javascript.

CodePudding user response:

The condition is set and can be checked on the server and the view is rendered on the server. That means you can simple use ERB to check the condition and then add a <script> block when it is true. The script block will run on the client.

# in the controller
def index
  @posts = Post.all.order(id: :desc)
  @post_loaded = @posts.length > 0
end

# in the view
<h1 >Posts</h1>
<div id="posts" data-controller="like" data-like-url-value="<%= like_posts_path %>">
  <div >
    <% @posts.each do |post| %>
        <%= render post %>
    <% end %>
  </div>
</div>

<% if @post_loaded %>
<script>
  console.log("All Posts has been loaded successfully.")
</script>
<% end %>
  • Related