请帮助解决问题。
我做了ajax-from用于在数据库中创建新记录:
<%= form_for [current_user, @album], :html => { 'data-current-user' => current_user.id } do |f| %>
<%= f.text_field :title %>
<%= f.submit %>
<% end %>
<table id="albumsList">
<thead>
<tr>
<th colspan="3"></th>
</tr>
</thead>
<tbody data-current-user="<%= current_user.id %>">
<% @albums.each do |album| %>
<tr>
<td><%= album.title %></td>
<td><%= link_to 'Show', user_album_path(current_user, album.id) %></td>
<td><%= link_to 'Edit', edit_user_album_path(current_user, album) %></td>
<td><%= link_to 'Destroy', user_album_path(current_user, album), method: :delete, data: { confirm: 'Are you sure?' } %>---<span class="destroy_album" data-album-id="<%= album.id %>">destroy</span></td>
</tr>
<% end %>
</tbody>
</table>
的application.js:
$('#new_album').on('submit', function(e){
e.preventDefault();
var currentUserId = $(this).attr('data-current-user'),
albumTitle = $('input#album_title').val();
$.ajax({
url: '/users/' + currentUserId + '/albums',
type: 'POST',
data: $('#new_album').serialize(),
success: function(result){
handleModal('album create', 'is successfull', '00ff2a', 2000);
$('#albumsList tbody').append('<tr> \
<td>' + albumTitle + '</td> \
<td></td> \
<td></td> \
<td><span class="destroy_album" data-album-id="??????">destroy</span></td> \
</tr>');
}
})
});
function handleModal(title, body, colorHex, timeout){
// bla bla bla
}
专辑控制器:
def create
@album = current_user.albums.build(album_params)
if @album.save
# @album_id = @album.id
redirect_to new_user_album_path(@current_user)
else
redirect_to new_user_album_path(@current_user), :status => 403
end
end
在结果用户提交表单并且:
但我需要元素.destroy_album
添加属性data-album-id和@ album.id值。为此我需要从控制器传递@ album.id到application.js和tpl.html.erb
答案 0 :(得分:2)
将此添加到type: 'POST'
dataType: "JSON",
当你正在制作json响应时,试试这个
def create
@album = current_user.albums.build(album_params)
if @album.save
render json: @album, status: ok
else
render json: @album, status: 403
end
end
现在成功了
您可以像这样检索ID
result.id