1

I have a database in which I add new records using Ajax requests and it works fine. By far I wrote a request which is adding properly new records right after already existing ones. I don't know what methods to use to add a new record when database is empty. How could adding request look like in my case? I'm sorry I'm only the beginner to Javascript. Thanks in advance.

views/tasks/create.js

$('.tasks').last().after("<%=j render partial: 'task', :locals => { :task => @task } %>");

views/tasks/_task.html partial

<tr class='tasks' id="task_<%= task.id %>">
  <td>
    <%= link_to user_task_path(current_user, task.id), method: :delete,
     data: { confirm: 'Are you sure?' }, remote: true do %>
      <i class="glyphicon glyphicon-trash"></i>
    <% end %>

    <a href="#" data-xeditable="true" data-pk="task" data-model='task' data-name='title'
      data-url="/users/<%= current_user.id %>/tasks/<%= task.id %>" data-title="Enter title">
      <i><%= task.title %></i>
    </a>

  </td>
</tr>

Here's my view file views/tasks/index.html file

   <h3>Tasks database</h3>

<table>
<% @tasks.each do |task| %>
<tr class='tasks' id="task_<%= task.id %>">
  <td>
    <%= link_to user_task_path(current_user, task.id), method: :delete,
     data: { confirm: 'Are you sure?' }, remote: true do %>
      <i class="glyphicon glyphicon-trash"></i>
    <% end %>

    <a href="#" data-xeditable="true" data-pk="task" data-model='task' data-name='title'
      data-url="/users/<%= current_user.id %>/tasks/<%= task.id %>" data-title="Enter title">
      <i><%= task.title %></i>
    </a>

  </td>
</tr>
<% end %>

<tr>
  <td><%= render 'form' %></td>
</tr>

</table>

enter image description here

1
  • There seems to be no ajax requests or databases in this code, if you mean .after() it's a method for inserting DOM elements ? Commented Jul 26, 2015 at 11:42

1 Answer 1

3

You can check if there are any .tasks present, and act accordingly

var tasks = $('.tasks');

if ( tasks.length > 0 ) {
    tasks.last().after("<%=j render partial: 'task', :locals => { :task => @task } %>");
} else {
    $('table').prepend("<%=j render partial: 'task', :locals => { :task => @task } %>")
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Although it works, the records appear below the input form when database is empty and not above it. Maybe you could know how to fix it?
And of course I would be pleased If you recommended some literature or guides so I can improve my knowledge of this
Try prepend instead, and you could start by reading the jQuery docs

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.