2012-12-27 64 views
1

我得到这个错误为什么我得到未定义的方法错误?

未定义的方法`created_at”的#ActiveRecord ::关联:0x0000001c3f57e8

控制器

@user = User.find_by_username(params[:username]) 
    @post = @user.comment_threads 

    if @post 
     last_time = @post.created_at 
     if Time.now - last_time <= 0.5.minute 
      redirect_to messages_received_path 
      flash[:notice] = "You cannot spam!" 
      return 
     end 
    end 
+0

由于'@ post'是模型实例的集合,而不是单个实例。 '@ user.comment_threads'必须返回一个集合(关系)而不是单个记录 –

回答

3

因为该行@post = @user.comment_threads返回ActiveRecord::Relation对象给你。最好在该句末尾加上.last.first,这样你就可以拥有一个Post对象。

2

@post = @user.comment_threads返回一个post对象的数组。因此created_at尝试在整个阵列上,而不是任何post对象。

这应该有所帮助。

if @post 
     last_time = @post.last.created_at 
     if Time.now - last_time <= 0.5.minute 
      redirect_to messages_received_path 
      flash[:notice] = "You cannot spam!" 
      return 
     end 
    end 
相关问题