我使用如下所示的友谊连接表在用户之间建立了自引用连接关系:
用户 > 友谊 > 用户(重命名的朋友)
在我的索引页面中,我希望有一个包含两个隐藏表单的按钮,用于根据关系状态在每个用户旁边创建和销毁好友或解除好友关系。我的创建关系工作正常,但对于销毁我遇到了一些问题。现在我正在处理 4 种可能性,每一种都有自己的问题。
jQuery
$(document).ready(function() {
$("li.friend-button").on('click', function(event) {
$(this).toggleClass('button-friended friend-button');
$(this).find("form.friend-form:hidden").submit();
});
$("li.button-friended").on('click', function(event) {
$(this).toggleClass('button-friended friend-button');
$(this).find("form.unfriend:hidden").submit();
});
});
再培训局
<li class="<%= friended ? "button-friended" : "friend-button" %>">Friend
<!-- From UsersController: @friendship = Friendship.new -->
<%= form_for [user, @friendship], :remote => true, html: { :class => 'friend-form'} do |f| %>
<%= f.submit %> #This creates fine
<% end %>
选项1:
<% friendship = current_user.friendships.find_by_friend_id(user.id)%>
<%= form_for friendship, :method => :delete, :remote => true, html: {class: "unfriend"} do |f| %>
<%= f.submit %> # Works as long as all users are friended, otherwise has error: undefined method `model_name' for NilClass:Class. Since the friendship is nil.
<% end %>
控制器
def destroy
@friendship = Friendship.find(params[:id])
@friendship.destroy
选项 2
<%= form_for user, :method => :delete, :url => friendship_path, :remote => true, html: {class: "unfriend"} do |f| %>
<%= f.submit %> # Error: No route matches {:action=>"destroy", :controller=>"friendships"}. Since it's form_for user, but heading to the FrendshipsController (I guess)
<% end %>
是的,我已经看到了:一个长期存在的错误阻止 form_for 自动使用单一资源。作为一种解决方法,直接指定表单的 URL,如下所示:form_for @geocoder, url: geocoder_path do |f|
从边缘指南
控制器
def destroy
@friendship = current_user.friendships.find_by_friend_id(params[:id])
@friendship.destroy
选项 3
<%= form_for [user, @friendship], :url => user_friendship_path, :remote => true, html: {class: "unfriend"} do |f| %>
<%= f.submit %> #Also: No route matches {:action=>"destroy", :controller=>"friendships"}, but no idea why
<% end %>
控制器
def destroy
@friendship = current_user.friendships.find_by_friend_id(params[:user_id])
@friendship.destroy
选项 4
<%= form_for [user, @friendship], :method => :delete, :remote => true, html: {class: "unfriend"} do |f| %>
<%= f.submit %>
<% end %> #Page finally renders, but get this from the dev.log:
Started DELETE "/users/4/friendships" for 127.0.0.1 at 2013-07-19 13:56:01 -0400
ActionController::RoutingError (No route matches [DELETE] "/users/4/friendships"):
控制器同O3
相关路线:
user_friendships POST /users/:user_id/friendships(.:format) friendships#create
user_friendship DELETE /users/:user_id/friendships/:id(.:format) friendships#destroy
friendship DELETE /friendships/:id(.:format) friendships#destroy
提前致谢。