0

我的代码是这个

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):
4

3 回答 3

2

利用:

@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).first
于 2013-08-07T08:12:24.623 回答
1

You are getting this error because the result of your method do not return a Tracking, but an array of Trackings.

Either you introduce more conditions to match only one Tracking, or use the first method or iterate over the results,

To use first:

@tracking = Tracking.where(:user_id => current_user.id, :target_user_id => @user.id).first

Iterate:

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
于 2013-08-07T08:19:52.443 回答
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

更多有用的方法在这里

于 2013-08-07T08:56:53.510 回答