我有一个Vendors
我正在迭代的列表,如下图所示。我正在尝试为每个供应商实现一个“最喜欢”或“喜欢”按钮。我在让它工作时遇到了一些麻烦。这是我的看法:
vendors/show.html.erb
<% provide(:title, 'Stores') %>
<table class="table table-condensed table-hover">
<tr>
<th>Store Name</th>
<th>Store Address</th>
<th>Favorite</th>
</tr>
<% Vendor.all.each do |v| %>
<tr>
<td><%= v.name %></td>
<td><%= v.address %></td>
<td>
<div id="like">
<%= render 'layouts/like_button', :vendor => vendor %>
</div>
</td>
</tr>
<% end %>
</table>
我的控制器:
class VendorsController < ApplicationController
def index
@vendors = Vendor.all
end
end
class LikesController < ApplicationController
# respond_to :js
def create
@like = Like.create(likes_params)
@vendor = @like.vendor
render :toggle
end
def destroy
like = Like.find_by_id(:id)
like.destroy
@vendor = like.vendor
render :toggle
end
private
def likes_params
params.permit(:id, :user_id, :vendor_id)
end
end
而我的部分_like_button.html.erb
:
<%= form_tag("/likes", method: "delete", action: "destroy", :remote => true) do %>
<%= hidden_field_tag(:id, vendor.likes.find_by_user_id(current_user.id).id) %>
<%= submit_tag("Unlike") %>
<% end %>
<%= form_tag("/likes", method: "post", :remote => true) do %>
<%= hidden_field_tag(:user_id, current_user.id) %>
<%= hidden_field_tag(:vendor_id, vendor.id) %>
<%= submit_tag("Like") %>
<% end %>
我的 toggle.js.erb 文件:
$("#like").html("<%= escape_javascript render('like_button') %>");
我目前收到此错误:“找不到 id=vendor 的供应商”所以不知何故,供应商一词作为 id 传入,但我不知道在哪里或如何修复它。我没有用 ajax 或 javascript 做太多事情,所以我对此很陌生。我一直在尝试遵循此示例应用程序的功能:https ://github.com/sergeylukin/soquestion6482354/blob/master/app/views/products/show.html.erb
请帮忙?提前致谢!
编辑注释
我更新了我的代码以反映我所做的更改。我不得不将它与表单混合在一起,因为我在迭代时无法让 form_for 工作。我目前可以likes
使用正确的参数通过 ajax 提交,但是我仍然无法提交unlikes
。我也没有看到我的页面更新了新的likes
附加内容。正如我所说,我对 js 和 ajax 非常熟悉,所以我不确定为什么。谢谢您的帮助!
模型更新
class Vendor < ActiveRecord::Base
has_many :inventory_items
has_many :items, through: :inventory_items
has_many :shopping_lists, through: :inventory_items
has_many :likes
has_many :liking_users, :through => :likes, :source => :user
end
class User < ActiveRecord::Base
has_many :shopping_lists
has_many :likes
has_many :liked_vendors, :through => :likes, :source => :vendor
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :vendor
end