mgh
mgh

Reputation: 1021

undefined method `each' in rails

In a rails project, I use below code to retrieve data from Assignmenttable in database and show to user:

views/assignmenttables/_form.html.erb

<% task_list = Assignmenttable.find_by_current_user_id(user.id) %>
  <% if task_list.blank? %>
  <h1>It's blank</h1>
  <% else %>
    <% task_list.each do |task| %>
        <%= task.id %>
    <% end %>
<% end %>

data is retrive correctly from database, if task_list isn't empty this code is correct, but when task_list is empty, I get below error:

undefined method `each' for #<Assignmenttable:0x000000069541c8>

how can I handle this error?

Upvotes: 1

Views: 60

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

The error you've got is caused because the object you called the .each method for is not a collection (multiple) - it's singular


Where

The way to fix this is to either use the .where method to call your data:

<%= task_list = Assignmenttable.where(user_id: current_user.id) %>

--

Associations

Or a better way will be to refactor your code to use the ActiveRecord associations which make Rails so appealing:

#app/models/user.rb
has_many :assignments

#app/models/assignment.rb # -> notice the name
belongs_to :user

current_user.assignments #-> allows you to call this in views

--

Model Names

Another thing you need to consider is your model names need to use CamelCase (AssignmentTable)

Upvotes: 1

Related Questions