associations - Rails - counting instances where boolean is true -
i trying make app rails 4.
i have project model , project invitations model.
projects has many project invitations project invitations belong projects
in project show, im trying count how many invitations have been sent , how many have been accepted.
the first part works fine. acceptances, have attribute in project_invitation table called :student_accepted. if true, want count record.
<%= @project.project_invitations.size %> <% if @project.project_invitations.student_accepted == true %> <%= @project.project_invitations.size %> <% else %> 'no' <% end %>
it gives error:
undefined method `student_accepted' #<activerecord::associations::collectionproxy []>
i have tried:
<% if project.project_invitations.student_accepted == true %> <%= project.project_invitations.size %>
it gives error:
undefined local variable or method `project' #<#<class:0x007fc01d9dcbe8>:0x007fc01de04248>
im struggling understand how reference attributes though associated models. have read several books assume background knowledge. i've had helpful input on related questions (below), still not grasping concept.
http://stackoverflow.com/questions/32916133/rails-how-to-show-attribute-of-an-associated-model http://stackoverflow.com/questions/32898541/rails-how-to-show-attributes-from-a-parent-object
can see i've done wrong?
you can find number of invitations students have accepted with:
@project.project_invitations.where(student_accepted: true).count
rails's active record query interface guide explains how works.
the reason received undefined method 'student_accepted' #<activerecord::associations::collectionproxy []>
error because calling student_accepted
on activerecord::associations::collectionproxy
, object rails creates define collection of records.
if wanted iterate on collection do:
<% @project.project_invitations.each |invitation| %> # here can call `invitation.student_accepted` <% end %>
this necessary because project has many invitations.
Comments
Post a Comment