1

please help solve the problem.

i did ajax-from for create new records in database:

<%= 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
}

albums controller:

  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

in result user submit the form and:

  1. make a new record in database through ajax-request.
  2. in the table added a new line with album name

but i need for element .destroy_album add the attribute data-album-id with @album.id value. for this i need pass @album.id from controller to application.js and to tpl.html.erb

1 Answer 1

2

add this to your ajax request above type: 'POST'

 dataType: "JSON", 

as you are making json response, try this

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

now on success

you can retrieve the id like this

result.id
Sign up to request clarification or add additional context in comments.

Comments

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.