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..
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.
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.
find_by
returns the first item. I think you are looking for
Bid.where(person_id: params[:person_id])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With