【问题标题】:ArgumentError: wrong number of arguments (given 1, expected 2) for Update_Attribute MethodArgumentError:Update_Attribute 方法的参数数量错误(给定 1,预期 2)
【发布时间】:2026-02-13 23:10:01
【问题描述】:

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

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

  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

Relationships.rb

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

def unfavorite
    update_attribute(favorited: false)
end

谁能帮我找出缺失的论点并解决这个问题。谢谢。

【问题讨论】:

  • 提出的错误相当清楚。 update_attribute 方法需要 2 个参数,而您正在传递一个(哈希)。将其更改为update_attribute(:favorited, true)
  • 谢谢!我知道这是一个愚蠢的错字,但我看不到它。

标签: ruby-on-rails model update-attributes argument-error


【解决方案1】:

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

【讨论】:

    最近更新 更多