简体   繁体   中英

Structuring a Rails app with javascript

Simple question,

in rails App, made a scaffold

rails g scaffold Post title:string body:string

i want to add simple condition in front-end javascript

if the @posts exists, alert("exist") else, alert("no posts")

I can add this scripts inside views/posts/index.html.erb

<script>
    $(function () {
        if (<%=@posts.length%> > 2)
            alert("exist");
        else
            alert("no posts");
    });
</script>

<h1>Listing posts</h1>

<table>
  <thead>
  <tr>
    <th>Title</th>
    <th>Body</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
  </thead>

  <tbody>
  <% @posts.each do |post| %>
      <tr>
        <td><%= post.title %></td>
        <td><%= post.body %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: {confirm: 'Are you sure?'} %></td>
      </tr>
  <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Post', new_post_path %>

the problem is,

<script>
    $(function () {
        if (<%=@posts.length%> > 2)
            alert("exist");
        else
            alert("no posts");
    });
</script>

i want to seprated this to an individual js file.

so, i have put this code in

assets/javascripts/posts.js

  $(function () {
            if (<%=@posts.length%> > 2)
                alert("exist");
            else
                alert("no posts");
  });

but in here, it cannot use <%=%> this rails view stuff :(

Is there are good solution?

You could add a data attribute to your table with post count, and perhaps a class to only listen on certain pages. Something like:

# view
body class=controller_name
  table data-posts-count=@posts.length

.

# js
$("body.posts").load(function() {
  count = $(this).data("posts-count")

  if count > 2
    alert("exist");
  else
    alert("no posts");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM