Rails - 计算布尔值为true的实例

时间:2015-10-03 00:27:10

标签: ruby-on-rails associations

我正在尝试使用Rails 4制作应用程序。

我有一个项目模型和项目邀请模型。

Projects has many project invitations
Project invitations belong to projects

在我的项目展示中,我试图计算已发送了多少个邀请以及已接受了多少个邀请。

第一部分工作正常。对于接受,我在project_invitation表中有一个名为:student_accepted的属性。如果这是真的,我想计算记录。

<%= @project.project_invitations.size %>
            <% if @project.project_invitations.student_accepted == true %>
                <%= @project.project_invitations.size %>
                <% else %>
                'No'
            <% end %>

它给出了这个错误:

undefined method `student_accepted' for #<ActiveRecord::Associations::CollectionProxy []>

我也尝试过:

<% if project.project_invitations.student_accepted == true %>

<%= project.project_invitations.size %>

它给出了这个错误:

undefined local variable or method `project' for #<#<Class:0x007fc01d9dcbe8>:0x007fc01de04248>

我很难理解如何通过相关模型引用属性。我读过几本书,但都是背景知识。我已经对相关问题提供了有用的意见(下文),但仍然没有掌握这个概念。

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

谁能看到我做错了什么?

2 个答案:

答案 0 :(得分:2)

您可以找到学生已接受的邀请数量:

@project.project_invitations.where(student_accepted: true).count

Rails的Active Record Query Interface guide解释了它是如何运作的。

您收到undefined method 'student_accepted' for #<ActiveRecord::Associations::CollectionProxy []>错误的原因是因为您在student_accepted上调用了ActiveRecord::Associations::CollectionProxy,这是一个用于定义记录集合的对象rails。

如果你想迭代那个集合,你可以这样做:

<% @project.project_invitations.each do |invitation| %>
  # here you can call `invitation.student_accepted`
<% end %>

这是必要的,因为项目有很多邀请。

答案 1 :(得分:1)

1) remove Microsoft.Mshtml.dll reference from your project. 2) Use ADD REFERENCE and choose BROWSE. 3) Point to "C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies" (it depends of x32/x64 systems) and select directly the microsoft.mshtml.dll file. 4) Set the COPY LOCAL = TRUE too. 为您提供了一个数组,而Array类没有方法@project.project_invitations(而数组中的每个项都有此方法)。

您可以使用student_accepted作为条件。

相关问题