Undefined method 'map' for nil:Nilclass

Asked

Viewed 496 times

0

I’m having this problem if the validator finds an error after submitting the form. I think it might be because my instance variable, @users, is nil?

I know it in the controller with before_action, so I shouldn’t have this problem, correct?

Controller:

class EnterprisesController < ApplicationController
  before_action :filter_user, only: [:new, :edit]

  def new
    @enterprise = Enterprise.new
    respond_with(@enterprise)
  end

  def edit
  end

  private
    def filter_user
      @users = User.where("role = 'customer' AND ID NOT IN ( SELECT user_id FROM ENTERPRISES WHERE USER_ID IS NOT NULL)")
    end
end

View:

<%= simple_form_for(@enterprise) do |f| %>
  <%= f.error_notification %>

  <div class="inputs">
    <%= f.input :name, label: 'Nome' %>
    <%= f.input :corporate_name, label: 'Razão Social' %>
    <%= f.input :phone, label: 'Telefone' %>
    <%= f.input :cnpj, label: 'CNPJ' %>
    <%= f.input :state_registration, label: 'Inscrição Estadual' %>
    <%= f.input :adress, label: 'Endereço' %>
    <%= f.input :number, label: 'Número' %>
    <%= f.input :district, label: 'Bairro' %>
    <%= f.input :city, label: 'Cidade' %>
    <%= f.input :cep, label: 'CEP' %>
    <%= f.label :user_id, 'Usuário' %>
    <%= f.collection_select(:user_id, @users, :id, :email, {include_blank: true}) %>
  </div>

  <div class="actions">
    <%= f.button :submit %>
  </div>
<% end %>

I searched on the Internet what could be, and found a solution; consult the bank directly from the view. But this violates the MVC principles, so I would have to check the Controller itself, but I can’t solve the problem.

  • Where is the error? No collection_select?

  • Yes. He says that the instance variable is nil.

  • you ran this filter_user query on the console? it returns data?

  • Yes, normal. Only when Activerecord returns some form fill error, it gives this problem.

  • A good practice is to avoid sharing controller instance variables with the display layer. A slightly better solution is to define a method users in the controller that returns the collection of users and passes it directly to the f.collection_select. This way you define a public interface for your controller (and signals a view dependency for this method. Then there would be no need for a before_filter, since the method will be executed when needed only (when explicitly called).

  • For example, I would define a users_collection method, and call the method that way? f. collection_select users_collection()

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.