1

我有一组用户的 favourite_guidelines。在我的控制台中,它看起来像这样:

fg=User.first.favourite_guidelines
  User Load (73.9ms)  SELECT "users".* FROM "users" LIMIT 1
  FavouriteGuideline Load (0.2ms)  SELECT "favourite_guidelines".* FROM "favourite_guidelines" WHERE "favourite_guidelines"."user_id" = 11
 => [#<FavouriteGuideline id: 16, guideline_id: 24, user_id: 11, created_at: "2013-02-17 01:03:19", updated_at: "2013-02-17 01:03:19">, #<FavouriteGuideline id: 18, guideline_id: 23, user_id: 11, created_at: "2013-02-17 11:40:27", updated_at: "2013-02-17 11:40:27">] 

所以它包含两个指导方针。我希望能够删除某个 guideline_id 的值,以便用户最喜欢的指南将删除该收藏。目前我有:

User.first,favourite_guidelines.delete_if{|favourite| favourite["guideline_id"] == 24}

这给了我:

.9.3p194 :066 > User.first.favourite_guidelines.delete_if{|favourite| favourite["guideline_id"] == 24}
  User Load (0.4ms)  SELECT "users".* FROM "users" LIMIT 1
  FavouriteGuideline Load (0.3ms)  SELECT "favourite_guidelines".* FROM "favourite_guidelines" WHERE "favourite_guidelines"."user_id" = 11
 => [#<FavouriteGuideline id: 18, guideline_id: 23, user_id: 11, created_at: "2013-02-17 11:40:27", updated_at: "2013-02-17 11:40:27">]'

所以看起来它正在删除它,但显​​然没有保存,因为如果我这样做:

    1.9.3p194 :067 > User.first.favourite_guidelines
  User Load (0.4ms)  SELECT "users".* FROM "users" LIMIT 1
  FavouriteGuideline Load (0.4ms)  SELECT "favourite_guidelines".* FROM "favourite_guidelines" WHERE "favourite_guidelines"."user_id" = 11
 => [#<FavouriteGuideline id: 16, guideline_id: 24, user_id: 11, created_at: "2013-02-17 01:03:19", updated_at: "2013-02-17 01:03:19">, #<FavouriteGuideline id: 18, guideline_id: 23, user_id: 11, created_at: "2013-02-17 11:40:27", updated_at: "2013-02-17 11:40:27">]

我究竟做错了什么?

4

2 回答 2

1

delete_if适用于返回记录的数组,但不适用于数据库。尝试:

User.first.favourite_guidelines.where(guideline_id: 24).destroy_all

PS。你也可以看看这里

于 2013-02-17T11:54:24.707 回答
1

试试这个:

   User.first.favourite_guidelines.destroy( :guideline_id => 24)

或者

  User.first.favourite_guidelines.where( :guideline_id => 24).destroy_all
于 2013-02-17T12:02:15.953 回答