为什么我得到未定义的方法'保存'错误?

时间:2013-08-07 08:11:07

标签: ruby-on-rails ruby-on-rails-3

我的代码就是这个

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

3 个答案:

答案 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