简体   繁体   English

Rails ajax 创建新记录

[英]Rails ajax create new record

I have a list of items with a "like" button on each item.我有一个项目列表,每个项目上都有一个“喜欢”按钮。 I want to be able to save that user's like inline from the list without reloading the page.我希望能够在不重新加载页面的情况下从列表中内联保存该用户的喜欢。

index.html.erb index.html.erb

<% @items.each do |i| %>
  <%= link_to(i) do %>
    <div class="item" style="background-image: url('<%= i.image.url %>')">
      <div class="itemgradient">
        <div class="metadata">
          <div class="name"><%= i.name %></div>
        </div>
        <div class="actions">
          <div class="heart like">
            <div class="glyf">
            </div>
          </div>
          <div class="price">
            <%= number_to_currency(i.price).gsub(/\.00$/, "")%>
          </div>
        </div> 
      </div>
    </div>
  <% end %>
 <% end %>


<script type="text/javascript">
  $("div.like").on("click", function() {
    $.ajax("/restaurants/likeitem");
    $(this).removeClass("like");
    $(this).addClass("unlike");
  });
</script>

restaurants_controller.erb restaurant_controller.erb

def likeitem
    if current_user
      l = LikedItem.new(:user_id => current_user)      
      l.save!
    else
      # if not logged in, make them sign up
    end
  end

models/likeditem.rb模型/likeditem.rb

class LikedItem < ApplicationRecord
    belongs_to :user
    belongs_to :item
end

However, every time I'm clicking the like button, I'm getting this 500 error:但是,每次单击“赞”按钮时,都会收到此 500 错误:

Completed 422 Unprocessable Entity in 59ms (ActiveRecord: 0.4ms | Allocations: 8492)在 59 毫秒内完成 422 个不可处理的实体(活动记录:0.4 毫秒 | 分配:8492)

ActiveRecord::RecordInvalid (Validation failed: User must exist, Item must exist): ActiveRecord::RecordInvalid(验证失败:用户必须存在,项目必须存在):

How do I make sure I'm passing through the right item ID to that ajax put?我如何确保将正确的项目 ID 传递给该 ajax 放置?

In your ajax call you don't pass any item id to controller, to fix that you can do this:在您的 ajax 调用中,您不会将任何项目 ID 传递给控制器​​,以解决您可以执行以下操作:

1- Add data-attribute that contains item's id to div.like 1- 将包含项目 id 的数据属性添加到 div.like

<div class="heart like" data-id="<%= i.id %>">
  <div class="glyf"></div>
</div>

2- Add item's id to ajax call 2- 将项目的 id 添加到 ajax 调用

<script type="text/javascript">
  $("div.like").on("click", function() {
    var $this = $(this) 
    $.ajax({
      url: "/restaurants/likeitem", 
      data: {
        item_id: $this.data("id")
      }
    })
    $(this).removeClass("like");
    $(this).addClass("unlike");
  });
</script>


After that you can access item_id in controller:之后,您可以在控制器中访问 item_id:

def likeitem
  if current_user
    l = LikedItem.new(:item_id => params[:item_id], :user_id => current_user)      
    l.save!
  else
    # if not logged in, make them sign up
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM