2017-12-25 11 views
0

私はRailsの初心者です。私は特定のトピックの下にある投稿のリストを表示したい。 これは私のコントローラです:NoMethodError in Post#インデックス未定義のメソッド `each 'for#<Post:0x9c01d58>

 def index 
     @posts = Post.find(params[:topic_id]) 
     end 

これが私の見解です:

 <% @posts.each do |p| %> ------>Error here 
     <tr> 
      <td> <%= p.user_id %> </td> 
      <td> <%= p.title %> </td> 
      <td> <%= p.content %> </td> 
      <td> <i> <%= p.created_at %> </i> </td> 
      <td> <%= link_to 'Show Post', post_path(p) %> </td> 
      <td> <%= link_to 'Delete Post', post_path(p), method: :delete %> </td> 
      <td> <%= link_to 'Update Post', edit_post_path(p) %> </td> 
     </tr> 
     <% end %> 

私はNoMethodError in Post#index (undefined method 'each' for #<Post:0x9c01d58>)でエラーが発生します。私はエラーが何であるか分からない。エラーがどこにあるのか教えていただけますか?

答えて

1

私は1つのポストを返すPost.findエラー

が何であるかを知りません。当然のことながら、それはeachには反応しません。なぜなら、それは単なる投稿であり、投稿の集まりではないからです。あなたはおそらく望ん

はこれです:

@posts = Post.where(topic_id: params[:topic_id]) 

が、それは言うのは難しいです。

1

Post.find(params[:topic_id])は、配列ではなくPostモデルの1つのインスタンスを取得します。

@posts = Post.all

はすべて

@posts = Post.where(topic_id: params[:topic_id])が話題

@posts = Post.where(user_id: params[:user_id])のためのすべての記事を検索します投稿取り出し、すべてのユーザーの投稿を検索し

関連する問題