2012-12-27 63 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 
相關問題