销毁has_many:通过不使用link_to帮助程序

时间:2015-08-14 15:57:46

标签: ruby-on-rails ruby

我正在使用Rails 4中的一个简单的项目管理工具,让我头疼的部分有三个主要模型:ProjectsUsersMemberships

用户可以有很多项目,项目可以有很多用户。我以下列方式在Projects和Users之间实现了has_many through成员关系:

项目:

class Project < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
end

用户:

class User < ActiveRecord::Base
   has_many :memberships
   has_many :projects, through: :memberships
end

成员:

class Membership < ActiveRecord::Base
    belongs_to :user
    belongs_to :project
end

到目前为止,我还没有在Stack Overflow上看到它,但我为成员资格创建了一个单独的控制器,只有:create:destroy。 到目前为止,:create似乎工作正常。

主要问题在于会员资格的销毁功能。 我实现的销毁功能是:

def destroy
    Membership.find(:id).destroy
    redirect_to current_project || request.referer
end

rake routes表示会员资格路径存在,但以下尝试给我:

我尝试使用link_to helper删除会员资格:

<%= link_to "delete", membership, method: :delete %> 
EDIT: error: undefined local variable or method `membership' 

<%= link_to "delete", @membership, method: :delete %>
EDIT: error: Sorry something went wrong --> goes to /memberships

<%= link_to "delete, membership_path(@membership), method: :delete %>
EDIT: error No route matches {:action=>"destroy", :controller=>"memberships", :id=>nil} missing required keys: [:id]

都会出错。

编辑:根据要求还提供projects_controller #show功能

def show
    @user = current_user
    @project = current_user.projects.find(params[:id])
    @members = @project.users
    @projects = @user.projects
    @membership = @project.memberships.build if logged_in?
    @memberships = @project.memberships
end 

如何确保使用@project.membership_ids中的关联ID删除成员身份?我应该包含一些额外的参数吗?

2 个答案:

答案 0 :(得分:0)

resources :memberships, only: [:create, :destroy]

更新

在你的摧毁行动Membership.find(:id).destroy中,不知道我早些时候错过了这个。它应该利用params并且更符合这一点:

# MembershipsController
def destroy
    @membership = Membership.find(params[:id])
    if @membership.destroy
        redirect_to current_project || request.referer
    else
        #
    end
end

您的ProjectsController显示操作并未将@membership定义为Membership个对象。

def show
    @user = current_user
    @project = @user.projects.find(params[:id])
    @membership = Membership.find_by user: @user, project: @project

    # build is used for nested attributes, not sure why you'd have this in a show action...
    # @project.memberships.build if logged_in?

    # the following are redundant.
    @projects = @user.projects
    @members = @project.users
    @memberships = @project.memberships
end 

在视图中:<%= link_to "delete", @membership, method: :delete %>

如果您希望在删除父项后销毁项目或用户的所有成员资格,请对User&amp; Project型号:

class Project < ActiveRecord::Base
    has_many :memberships, dependent: :destroy
    has_many :users, through: :memberships
end

class User < ActiveRecord::Base
    has_many :memberships, dependent: :destroy
    has_many :projects, through: :memberships
end

答案 1 :(得分:-1)

您的代码无效的原因是您没有指定link_to的路径。我不相信你需要@membership所以我编辑了它。

<%= link_to "delete", membership_path(@membership), method: :delete %>