2014-07-27 76 views
0

我試圖列出當前登錄的用戶的待辦事項列表。我正在使用設計作爲我的身份驗證寶石。每條語句都不能遍歷current_user.id

的代碼是這樣:

class TodosController < ApplicationController 
    def index 
    if user_signed_in? 
     @todo_items = Todo.all.find_by_user_id(current_user.id) 
     @new_todo = Todo.new 
    else 
     redirect_to new_user_session_path 
    end 
    end 
end 

但是當我運行此我得到這個錯誤

undefined method `each' for #<Todo:0x38b8d68> 

我的循環語句是:

<div class="well"> 
    <% @todo_items.each do |t| %> **#error in this line.** 
    <li> <%= t.todo_item %> </li> 
    <% end %> 
</div> 

我不知道是什麼我做錯了。 我也試過

@todo_items = Todo.all.find_by_user_id(params[:current_user.id]) 

我仍然得到相同的錯誤。 我對此很新,而且現在還沒有使用任何教程,因此請嘗試從新手角度解釋您的答案。謝謝

+0

基本上spickermann回答它,你也可以重構這個,因爲你不if條件 - 設計得到了一個幫手。它被稱爲before_filter:authenticate_user !. –

+0

我瞭解我正在使用的部分。我在那裏使用而且像魅力一樣工作。是的,我閱讀了有關之前的文件,並用它來代替「如果」。謝謝回覆。 –

回答

0

當您運行這

Todo.all.find_by_user_id(current_user.id) 

首先,

Todo.all will return all the user records 

,你應用find_by_user_id上Todo.all,因爲我們知道find_by方法返回一個記錄

顯然,

Todo.all.find_by_user_id 

將返回單個記錄,因爲你發現來自所有用戶的單個用戶。

而你正試圖遍歷導致錯誤的單個記錄。

<% @todo_items.each do |t| %> **#error in this line.** 
<li> <%= t.todo_item %> </li> 
<% end %> 

嘗試以不同的方式,

Todo.find_all_by_user_id(current_user.id) 
    (or) 
Todo.where(:user_id => current_user.id) 
    (or) 
Todo.all(:where => "user_id => #{current_user.id}") 

上述任何會工作。

+0

我嘗試了所有,但有部分在線時有差異。比如速度和響應時間?......哪一個是首選?......感謝您的答覆......選擇了您的答案......感謝您的詳細解答。 –

+0

感謝您接受我的回答。 Model.find(:all)或model.find_by()方法從rails rails 4及更高版本中棄用,如果要使用rails 4的最新版本,則必須使用model.where()。你可以在http://blog.remarkablelabs.com/2012/12/what-s-new-in-active-record-rails-4-countdown-to-2013查看詳細的視圖 –

0

find_by_user_id(...)是一樣的像where(:user_id => ...).first並只返回一個項目。你可能想使用:

Todo.where(:user_id => current_user.id) 

什麼返回一個數組(和響應each)。甚至更好:如果我們的用戶模型有has_many協會todos只寫:

current_user.todos 
+0

謝謝...修正了它 –

0

你的代碼看起來像什麼

class TodosController < ApplicationController 
    def index 
    if user_signed_in? 
    @todo_items = Todo.where(user_id: current_user.id) 
    @new_todo = Todo.new 
    else 
    redirect_to new_user_session_path 
    end 
    end 
    end 

然後

<div class="well"> 
    <% @todo_items.each do |t| %> **#error in this line.** 
    <li> <%= t.todo_item %> </li> 
    <% end %> 
    </div>