LoginSignup
3

More than 5 years have passed since last update.

Rails: viewでany?を使うときに気をつける点

Posted at

ケース:feed_itemsをviewで表示させる

エラー: undefined method any? for nil:NilClass

なぜか: @feed_itemsのfeedがない
    =>nilを返す
    =>nilはany?メソッドを持っていない
    =>エラー

どうすればいいか: feedtodoなので、todos_controllercreateメソッドに@feed_items = []を追加してnilを避ける。
 

###static_pages_controller.rb
class StaticPagesController < ApplicationController
  def home
    if signed_in?
        @todo = current_user.todos.build
        @feed_items = current_user.feed.paginate(page: params[:page])
    end
  end
end
###User.rb
def feed
  # This is preliminary. See "Following users" for the full implementation.
  Todo.where("user_id = ?", id)
end
<!--home.html.erb-->
 <% if @feed_items.any? %>
  <ol class="todos">
      <%= render partial: 'shared/feed_item', collection: @feed_items %>
  </ol>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3