我的代码就是这个
def footstamp
if current_user
@user = User.find(params[:id])
@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id)
if @tracking
@tracking.accessed_at = Time.now
@tracking.save
else
@tracking = Tracking.new
@tracking.user_id = current_user.id
@tracking.target_user_id = @user.id
@tracking.accessed_at = Time.now
@tracking.save
end
end
end
然后我收到此错误
NoMethodError (undefined method `save' for []:ActiveRecord::Relation):
答案 0 :(得分:2)
使用:
@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).first
答案 1 :(得分:1)
您收到此错误是因为您的方法的结果不会返回Tracking
,而是返回Trackings
的数组。
您要引入更多条件以仅匹配一个Tracking
,或使用first
方法或迭代结果,
首先使用:
@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).first
迭代:
Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).each do |tracking|
if tracking
tracking.accessed_at = Time.now
tracking.save
else
tracking = Tracking.new
tracking.user_id = current_user.id
tracking.target_user_id = @user.id
tracking.accessed_at = Time.now
tracking.save
end
end
答案 2 :(得分:0)
优化答案,
def footstamp
if current_user
@user = User.find(params[:id])
@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).first_or_create
@tracking.accessed_at = Time.now
@tracking.save
end
end
更有用的方法here