Question

OK, I am new to rails but trying to learn so my apologies if this question exposes my lack of knowledge!

I have a very simple application with 2 models (Building & Customise) and 2 Controllers (Buildings & Customises) each with an index view.

My root is buildings#index

Within buildings#index view I am trying to access data from both models along the lines of:

    <div class="wrap">
            <header>

                <% @setup.each do |customise| %>

                <h1><%= customise.title %></h1>

                <% end %>

Where in my buildings controller I have defined:

    def index

@buildings = Building.all
@unis = Building.where(buildingtype: "uni")

if params[:parentd].present?
@buildings = Building.where("university = ? OR buildingtype = 'directlet'", params[:parentd])

@setup = Customise.all

end

This yields the following error:

ActionView::Template::Error (undefined method `each' for nil:NilClass):
4:  
5: <% end %>
6: 
7: <% @unis.each do |uni| %>
8: <option value="<%= uni.name %>"><%= uni.name %></option>
9: <% end %>
app/views/customises/index.html.erb:7:in 
  `_app_views_customises_index_html_erb__589235851577785880_2190604320'

My reading suggests that accessing data from two models in any view is possible which led me to believe that there is something wrong with my notation.

However, when I try to access the same model information, in the same way but within a view associated with the customises controller the data shows without error.

Can anybody suggest the reason behind this?

Was it helpful?

Solution 2

In your controller, the if condition is not getting satisfied, so @setup is nil. Make sure @setup gets initialized.

OTHER TIPS

Is your Customise Model contains any data? If yes then please check your condition that is

if params[:parentd].present?

you are not getting your params that is [:parentd]

The error undefined method `each' for nil:NilClass indicates that you have tried to call method #each on nil class's instance

In your case @unis is nil (from the log you provided).

You can either make sure that @unit is never nil in controller. Or try to put in it in if..else block in your view.

For example:

<% if @unit.nil? %>
  <%# Show message regarding nil value of @unit %>
<% else %>
  <%# Your normal logic of showing @unit %>
<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top