Undefined method every Ruby

Launch. A person can have many bets, this particular person has only one bet.

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

In my opinion, I do

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

I get NoMethodError: undefined method each' for #<Bid:0x007f988a346f00> when displaying an index for individual bets.

Is it because this person has only one bet? I feel that this is not so, but other than that they fail.

+5
source share
2 answers

find_by returns the first element. I think you are looking

 Bid.where(person_id: params[:person_id]) 
+12
source

Austio correct answer.

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

A person can have many bets.

You are obviously creating 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 create a collection without calling where .

Of course, your method uses only one db request. But even with the above, it is much more intuitive.

-

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

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

The presence of one bet is in order, but the absence of any of them will not lead to the allocation of errors. The above fixes this problem.

+2
source

Source: https://habr.com/ru/post/1234567/


All Articles