Rails - 部分使用JS呈现时ID错误

时间:2015-03-24 20:30:06

标签: ruby-on-rails ajax

我在Rails中使用Ajax来创建/销毁预留。

问题是当我尝试删除预订时,有时候预订ID显示为相同,而不是最后创建的。

删除预约并尝试创建其他预留后,会出现此问题。

以下是代码:

# controllers/reservation_controller.rb
def create
  @reservation = Reservation.new(reservation_params)

  respond_to do |format|
    if @reservation.save
      format.html { redirect_to @reservation }
      format.json { render :show, status: :created, location: @reservation }
      format.js   { render :layout => false }
    else
      format.html { render :new }
      format.json { render json: @reservation.errors, status: :unprocessable_entity }
      format.js   { render :layout => false }
    end
  end
end

def destroy
  @day  = @reservation.day
  @hour = @reservation.hour
  @reservation.destroy
  respond_to do |format|
    format.html { redirect_to reservations_url }
    format.json { head :no_content }
    format.js   { render :layout => false }
  end
end

观点部分:

<% hours.each do |hour| %>
  <tr>
      <th><%= hour %></th>
      <% days.each do |day| %>
        <td>
          <% reservation = get_reservation(day.downcase, hour) %>
          <% if reservation %>
            <% if reservation.user_id == current_user.id %>
              <%= render :partial => 'reserved_room', :locals => { reservation: reservation } %>
            <% else %>
              Reserved to <%= reservation.user.name %>
            <% end %>
          <% else %>
              <%= render :partial => 'available_room', :locals => { day: day, hour: hour } %>
          <% end %>
        </td>
      <% end %>
  </tr>
<% end %>

部分:

<%= link_to "Reserved to #{reservation.user.name}", 
  {controller: :reservation, action: :destroy, id: reservation.id}, method: :delete, remote: true, :class => 'cancel_reservation' %>

和JS:

$('.create_reservation').bind('ajax:success', function() {
  $(this).parent().html('<%= j render :partial => 'reserved_room', :locals => { reservation: @reservation } %>');
});

可以测试项目here

0 个答案:

没有答案