Home > OS >  Getting error ActionView::Template::Error (undefined method `each' for nil:NilClass)
Getting error ActionView::Template::Error (undefined method `each' for nil:NilClass)

Time:05-23

I tried to pass some string from a Controllers method to view but it is giving error ActionView::Template::Error (undefined method `each' for nil:NilClass):

These are my code's i tried:

ApplicationController.rb

class ApplicationController < ActionController::Base
private
    def baconipsum
        @baconipsum ||= Faraday.new("https://baconipsum.com/") do |f|
          f.response :json
        end
      end
end

ArticlesController.rb

def show_Data
    #@count = params[:count]
    @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
end

_show_data.html.erb

<% @bacon.each do |meat| %>
  <p><%= meat %></p>
<%end%>

Here I tried to take user input that how many paragraph he wants to generate and i will pass its value to controller show_data, so that Faraday will generate that number of paragraph for it

Here is my form view

_form_data.html.erb

<%= form_for:article do %>
    <label for="value">Value</label>
    <%= text_field_tag :value %>
    <%= submit_tag "Submit" %>
<% end %>

CodePudding user response:

# config/routes.rb
get "articles/show_data", to: "articles#show_data"

# app/controllers/articles_controller.rb
def show_data
  @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
  # NOTE: this action will `render "show_data"` by default
end                                        # |
                                           # |
# app/views/articles/show_data.html.erb <----'
<% @bacon.each do |meat| %>
  <p><%= meat %></p>
<% end %>

To see the result, go to http://localhost:3000/articles/show_data

Update

# app/controllers/articles_controller.rb
def show_data
  @bacon = baconipsum.get("api/", type: 'all-meat',paras: 2).body
end

def show
  @article = Article.find(params[:id])
  show_data # this will set `@bacon` variable
end
<!-- app/views/articles/_show_data.html.erb -->
<% bacon.each do |meat| %>
  <p><%= meat %></p>
<% end %>

<!-- app/views/articles/show.html.erb -->
<%= render "articles/show_data", bacon: @bacon %>

Update 2

Submit form to ArticlesController#show action:

<%= form_for :api_options, url: "/articles/1", method: :get do |f| %>
  <%= f.label :paras %>
  <%= f.text_field :paras %>

  <%= f.submit %>
<% end %>

ArticlesController#show calls show_data method. Submitted form parameters are available through params method in the controller:

def show_data
  @bacon = baconipsum.get(
    "api/",
    type: 'all-meat',
    # NOTE: use `fetch` method and set some defaults when params are not present.
    paras: params.fetch(:api_options, {}).fetch(:paras, 1)
  ).body
end

https://guides.rubyonrails.org/action_controller_overview.html#methods-and-actions

https://guides.rubyonrails.org/layouts_and_rendering.html#rendering-by-default-convention-over-configuration-in-action

  • Related