模型关联has_and_belongs_to_many删除对象?

时间:2014-02-23 17:48:04

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个模型项目,有很多短途旅行。

class Project < ActiveRecord::Base
  has_many :excursions

    def remove_user_from_excursion(excursion_id, current_user)
      excursions.find(excursion_id).users.delete(current_user)
      save!
    end
end

然后我有一个模型Excursions,其中包含has_and_belongs_to_many_users用户。

class Excursion < ActiveRecord::Base
  belongs_to :project
  has_and_belongs_to_many :users
end

我想提供从游览中删除用户的功能,我尝试在Project模型上调用 remove_user_from_excursion 方法,但它似乎不起作用。用户仍然是短途旅行的一部分。我做错了什么?

3 个答案:

答案 0 :(得分:0)

首先,你不能在数组上使用“find”。在你的情况下,你应该有一系列的短途旅行,你想通过id找到它,这将无法正常工作。 “find”方法适用于模型类,如“Excursion.find(excursion_id)”。

其次,你必须有一个“Project”实例才能获得与项目相关的短途旅行,所以你应该使用“self” - &gt; “self.excursions ......

最终,为了做你想做的事,你可以写下如下内容:

def remove_user_from_excursion(excursion_id, current_user)
    Excursion.find(excursion_id).users.delete(current_user)
end 

def remove_user_from_excursion(excursion_id, current_user)
    self.excursions.select{|p| p.id==excursion_id}.first.users.delete(current_user)
end

当然第一种选择要好得多:)

答案 1 :(得分:0)

excursion_instance.users.find(<user_id>).destroy应该做的工作。在这种关系中,destroy意味着销毁连接表中与两个实体相关联的记录,在本例中是表ExcursionsUsers。试一试。

答案 2 :(得分:0)

以下内容应该有效

def remove_user_from_excursion(excursion_id, current_user)
  excursions.find(excursion_id).users.destroy(current_user)
end