Jerrod
Jerrod

Reputation: 195

Targeting a class in the from the View

I'm using Ruby 2.0.0 and Rails 4.

I am trying to access the class I created below and iterate through it in the View. The puts line in my Controller is working correctly and outputting the data so I know it is properly being set.

However, when I try to print the items in the View it gives me the following error:

NoMethodError in Actions#list undefined method `each' for nil:NilClass

So obviously I am not targeting the class correctly. How should I be doing this? I have read several different questions / tutorials with no luck in implementation.

After following Mattherick's (further) instructions my code now looks like this:

Model:

class ListItem < ActiveRecord::Base
attr_accessor :value, :name, :type, :details, :available, :date, :id
#This calls and API which contains JSON data I am trying to display
def self.mylist
    mylist = folder_list('sub', 'tld', $myAuthID, path='/')
end

end

Controller:

class ListItemsController < ApplicationController
def new
    @list_item = ListItem.new
end

def index
    @list_item = ListItems.mylist
end
end

View:

<%= @list_items. each do |item| %>
<%= item.name %>
<% end %>

Upvotes: 0

Views: 52

Answers (2)

Matthias
Matthias

Reputation: 4375

I think you don't check the mvc pattern? :)

You cannot iterate over your class, you can iterate over objects of your class

# app/models/list_item.rb
class ListItem < ActiveRecord::Base
  attr_accessor :value, :name, :type, :details, :available, :date, :id

  # Update
  def self.mylist
    # your api call
  end

end

# app/controllers/list_items_controller.rb
class ListItemsController < ApplicationController

  def new
    @list_item = ListItem.new
  end

  # Update
  def index
   @list_items = ListItem.mylist
  end

end

# app/views/list_items/new
<%= form_for @list_item do |f| %>
  <% # your form fields %>
<% end %>

# app/views/list_items/index
<%= @list_items. each do |item| %>
  <%= item.name %>
<% end %>

More information about this basics: http://guides.rubyonrails.org/getting_started.html

And what do you want with your list-method?

UPDATE:

I updated the model and the index action of the controller.

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36870

@newList contains a single, new instance of ListItem. So you can't do the method .each on it.

If you want several objects in @newList you'd need to do

@newList = ListItem.all 

in the controller method (better to put it in the def index method rather than def new)

If you want to just access the single object, then you'd be better off forgetting the each loop and doing...

<td><%= @newList.name %></td>

Upvotes: 0

Related Questions