首页 > 解决方案 > ArgumentError:Update_Attribute 方法的参数数量错误(给定 1,预期 2)

问题描述

我正在创建一个定期事件应用程序,其中某些用户(流媒体)可以安排定期的每周事件(流),而其他用户(观众)可以关注它们。结果是个性化的每周日历,详细说明所有关注的彩带活动开始和结束的时间。

在此处输入图像描述

但是,由于观众可以关注无限数量的流媒体,因此生成的日历看起来就像一团糟。因此,我在关系表中添加了一个布尔属性,指示该关系是否已被收藏。

  create_table "relationships", force: :cascade do |t|
    t.integer "follower_id"
    t.integer "followed_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "favorited", default: false
    t.index ["followed_id"], name: "index_relationships_on_followed_id"
    t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
    t.index ["follower_id"], name: "index_relationships_on_follower_id"
  end

这样,观众将拥有第二个个性化日历,该日历将仅显示最喜欢的流媒体的事件。

我已经有一个关注和取消关注方法,可以成功地创建和破坏观众和流媒体之间的关系,但是我无法成功地将现有关系从不喜欢的更新为收藏。

test "should favorite and unfavorite a streamer" do
    yennifer = users(:yennifer)
    cirilla = users(:cirilla)
    yennifer.follow(cirilla)
    yennifer.favorite(cirilla)     #user_test.rb:151
end

测试套件返回以下错误,我无法弄清楚缺少的参数是什么。

["test_should_favorite_and_unfavorite_a_streamer", #<Minitest::Reporters::Suite:0x0000000006125da8 @name="UserTest">, 0.16871719993650913]
 test_should_favorite_and_unfavorite_a_streamer#UserTest (0.17s)
ArgumentError:         ArgumentError: wrong number of arguments (given 1, expected 2)
            app/models/relationship.rb:11:in `favorite'
            app/models/user.rb:124:in `favorite'
            test/models/user_test.rb:151:in `block in <class:UserTest>'

  27/27: [=================================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.82473s
27 tests, 71 assertions, 0 failures, 1 errors, 0 skips

用户.rb

# Follows a user
def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
end

# Unfollows a user
def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
end

def favorite(other_user)
    active_relationships.find_by(followed_id: other_user.id).favorite     #user.rb:124
end

def unfavorite(other_user)
    active_relationships.find_by(followed_id: other_user.id).unfavorite
end

关系.rb

def favorite
    update_attribute(favorited: true)     #relationship.rb:11
end

def unfavorite
    update_attribute(favorited: false)
end

有人可以帮我找出缺失的论点并解决这个问题。谢谢你。

标签: ruby-on-railsmodelupdate-attributesargument-error

解决方案


关于这个答案的第一条评论是正确的,所以我不知道为什么这个人发表评论而不是答案。update_attribute 接受两个参数,并且您传递给它一个哈希参数。你“最喜欢”的方法相当于 update_attribute({favorited: true})你真正想要的时候update_attribute(:favorited, true)


推荐阅读