Reputation: 812
I have two model classes - Admin and Bill. I am able to get them from the database using ActiveRecord but when I use an erb template, I cannot display the bills information (each admin can have multiple bills):
app.rb
get '/admins/:id' do
@admin = Admin.find_by(id:params[:id])
@bills = Bill.find_by(user_id:params[:id])
erb :adminDetails
end
adminDetails.erb
<ul>
<li>full name: <%[email protected] %></li>
<li>email: <%[email protected] %></li>
<% @bills.each do |bill| %>
<li>bill title: <%=bill.title %></li>
<li>bill body: <%=bill.body %></li>
<% end %>
</ul>
I can print out the bill info via irb but when I pass it into the erb template, I get the following exception:
WARN: tilt autoloading 'tilt/erb' in a non thread-safe way; explicit require 'tilt/erb' suggested.
2015-09-10 05:00:26 - NoMethodError - undefined method `each' for #<Bill id: 1, admin_id: 1, title: "test1", body: "this is test1">:
/usr/local/rvm/gems/ruby-2.2.1/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
/opt/test/ruby/7/views/adminDetails.erb:11:in `block in singleton class'
/opt/test/ruby/7/views/adminDetails.erb:-6:in `instance_eval'
/opt/test/ruby/7/views/adminDetails.erb:-6:in `singleton class'
/opt/test/ruby/7/views/adminDetails.erb:-8:in `__tilt_20667340'
Bill Model
class Bill < ActiveRecord::Base
belongs_to :admin
end
Is there something wrong with my setup causing this issue? Thanks in advance
Upvotes: 2
Views: 381
Reputation: 7482
Why don't you take bills from your @admin
variable?
You don't need @bills
in your controller anymore:
get '/admins/:id' do
@admin = Admin.find_by(id:params[:id])
erb :adminDetails
end
And use this for your template:
<% @admin.bills.each do |bill| %>
<li>bill title: <%=bill.title %></li>
<li>bill body: <%=bill.body %></li>
<% end %>
Upvotes: 1
Reputation: 44360
You trying to make an iteration through an one record. Bill.find_by(user_id:params[:id])
returns only an one record(first matched), fix your code to:
@bills = Bill.where(user_id: params[:id])
Read the documentation for where
and find_by
Upvotes: 4
Reputation: 5058
Your instance variable @bills
might not be enumerable. In other words @bills
might not be array of entity Bill
.
You're trying to iterate over
<Bill id: 1, admin_id: 1, title: "test1", body: "this is test1">
not even
[#<Bill id: 1, admin_id: 1, title: "test1", body: "this is test1">]
and that's because find_by
returns just first matching record based on the criteria.
Upvotes: 1