Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method each Ruby

The run down. A person can have many bids, this particular person only has one bid.

In my index action I have @bids = Bid.find_by_person_id(params[:person_id])

in my view I do

<% @bids.each do |bid| %>
   <%= bid.bid_amount %>
<% end %>

I am getting NoMethodError: undefined method each' for #<Bid:0x007f988a346f00> when visting the index view for person bids.

Is this because this person only has one bid? I feel thats not the case, but other than that im at a loss..

like image 282
Seal Avatar asked Oct 27 '15 02:10

Seal


People also ask

What is .first in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does undefined method mean in Ruby?

This is a common Ruby error which indicates that the method or attribute for an object you are trying to call on an object has not been defined.


2 Answers

find_by returns the first item. I think you are looking for

Bid.where(person_id: params[:person_id])
like image 73
Austio Avatar answered Oct 21 '22 06:10

Austio


Austio's answer is correct.

However, why are you calling the Bid model directly?...

A person can have many bids

You're obviously constructing data from the person model, so why not call the following:

@person = Person.find params[:person_id]
@bids = @person.bids #-> bids belong to @person

This will build the collection without calling where.

Of course, your method only uses a single db query. But even still, the above is much more intuitive.

--

As an aside, you'll also want to use a conditional before your loop:

<% if @bids.any? %>
   <% @bids.each.... %>
<% end %>

Having one bid is fine, but having none will cause the loop to spit out an error. The above resolves that issue.

like image 2
Richard Peck Avatar answered Oct 21 '22 06:10

Richard Peck