开发者

@user.visit_count => undefined method

开发者 https://www.devze.com 2023-01-23 01:07 出处:网络
I am doing what I thought was something very simple - finding a user and incrementing an integer. @user = User.where(\"created_at > ?\", Time.now.midnight).select(:visit_count)

I am doing what I thought was something very simple - finding a user and incrementing an integer.

@user = User.where("created_at > ?", Time.now.midnight).select(:visit_count)
@u开发者_Go百科ser.visit_count += 1
@user.save(:validate=>false)

I get the following error:

undefined method `visit_count' for [#<ActiveLink visit_count: 1>]:ActiveRecord::Relation

This seems like a Rails 3 thing - where am I going wrong?


Your query always returns multiple results as an Array.

Just add .first to be sure that you only pick the first result.

@user = User.where("created_at > ?", Time.now.midnight).select(:visit_count).first

If you want to update many records at the same time, look at update_all method :

http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all

0

精彩评论

暂无评论...
验证码 换一张
取 消