【问题标题】:Rails call destroy method from within another controllerRails 从另一个控制器中调用 destroy 方法
【发布时间】:2011-11-11 01:28:35
【问题描述】:

我有一个friendships_controller,但我想从users_controller 内部调用它的createdestroy 操作。实际上,按照我的设置方式,create 方法可以正常工作,但 destroy 不行。

用户/索引

<%= button_to "+ Add Friend", :controller => "friendships", :action => 'create', :method => "post", :id => user.id %>
<%= button_to "- Unfriend", {:controller => "friendships", :action => 'destroy'}, :confirm => "Are you sure you want to unfriend #{user.username}?", :method => :delete, :id => user.id %>

如果我点击取消好友按钮,我会收到以下异常:

ActiveRecord::RecordNotFound in FriendshipsController#destroy
Couldn't find User with ID=destroy

这是friendships_controller 中的destroy 操作:

  def destroy
    @accepting_user = User.find(params[:id])
    @friendship = Friendship.find_by_accepting_user_id_and_requesting_user_id(@accepting_user.id, current_user.id)
    @friendship.destroy
    flash[:notice] = "You unfriended #{@friendship.accepting_user.username}."
    redirect_to(:back)
  end

有人对此有任何想法吗?谢谢。

更新

友谊路线:

rake routes | grep friendship
           friendships_index GET    /friendships/index(.:format)                                      {:controller=>"friendships", :action=>"index"}
                 friendships GET    /friendships(.:format)                                            {:controller=>"friendships", :action=>"index"}
                             POST   /friendships(.:format)                                            {:controller=>"friendships", :action=>"create"}
              new_friendship GET    /friendships/new(.:format)                                        {:controller=>"friendships", :action=>"new"}
             edit_friendship GET    /friendships/:id/edit(.:format)                                   {:controller=>"friendships", :action=>"edit"}
                  friendship GET    /friendships/:id(.:format)                                        {:controller=>"friendships", :action=>"show"}
                             PUT    /friendships/:id(.:format)                                        {:controller=>"friendships", :action=>"update"}
                             DELETE /friendships/:id(.:format)                                        {:controller=>"friendships", :action=>"destroy"}

【问题讨论】:

  • 您可以发布您的routes.rb 文件吗?
  • 我在上面添加了友谊的路线;你真的更喜欢看 routes.rb 文件吗?

标签: ruby-on-rails-3 destroy


【解决方案1】:

搞定了,只需要移动到我在:id经过的地方

最终结果如下:

<%= button_to "- Unfriend", {:controller => "friendships", :action => 'destroy', :id => user.id}, :confirm => "Are you sure you want to unfriend #{user.username}?", :method => :delete %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多