Reputation: 2179
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>
Upvotes: 1
Views: 20
Reputation: 318202
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 } %>")
}
Upvotes: 3