试图从数组中删除 - rails

时间:2013-02-17 11:49:09

标签: ruby-on-rails ruby-on-rails-3

我有一个用户的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">]

我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

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

PS。你也可以看here

答案 1 :(得分:1)

试试这个:

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

或者

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