C.Yee
C.Yee

Reputation: 39

NoMethodError (undefined method `map' for nil:NilClass

Dear fellow rails programmers,

I am facing a little problem on my collection_select form_tag the project i am working on contains 3 seperate major models: customers, owners, addresses.

One customer can have multiple owners and addresses while each address can assign an owner

the problem i am facing is that i cant seem to assign owner to address

in my address controller new.html.erb

<%= form_for(@address) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <%= hidden_field_tag :id, @customer.id %>

  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>

  <%= f.label :unit %>
  <%= f.text_field :unit, class: 'form-control' %>

  <%= f.label :tel %>
  <%= f.text_field :tel, class: 'form-control' %>

  <%= f.label :working_hours %>
  <%= f.time_select :start_at, {minute_step: 30} %> to 
  <%= f.time_select :end_at, {minute_step: 30} %>

  <%= f.label :owner_id %>
  <%= f.collection_select :owner_id, @owners, :id, :name, {include_blank: 'Please Select'},%>
.
.
.
<%= f.submit "Add new address", class: "btn btn-primary" %>
<% end %>

in address.rb

def new
  @address = Address.new
  @customer = Customer.find(params[:id])
  @owners = Owner.find_by(customer_id: params[:id])
end

I am facing an error:

NoMethodError (undefined method `map' for nil:NilClass Did you mean? tap):

with the code above.. but when i replace

@owners = Owner.find_by(customer_id: params[:id])

with

@owners = Owner.all

this page will load and the select dropbox will allow me to select ALL OWNERS in my Owners table.. i would just like to search for Owners with customer_id = params[:id]..

P.S - both address and owner table has customer_id column and address.rb has_many :owners, and owner.rb belongs_to :address

Can anybody help me? thanks and much appreaciated.

Upvotes: 0

Views: 5192

Answers (2)

Pascal
Pascal

Reputation: 8656

find_by returns a single record or nil. Neither of these objects support map. This is why you see the error message.

You should use where:

@owners = Owner.where(customer_id: @customer.id)

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230531

Owner.find_by returns at most one record. Whereas you need a collection. Use this instead:

@owners = Owner.where(customer_id: @customer.id)

Upvotes: 2

Related Questions