【发布时间】:2016-08-15 23:09:33
【问题描述】:
我正在尝试学习如何编写一个方法来计算我的 Rails 4 应用程序中的用户项目。
我有名为 Project 和 Profile 的模型。这些关联是:
项目
belongs_to :profile
简介
has_many :projects
在我的项目模型中,我有一个按 profile_id 查找项目的范围。
scope :by_profile, ->(profile_id) { where(profile_id: profile_id) }
现在,我正在尝试编写方法来计算配置文件已进行了多少项目。
def project_counter
# projects created by this project creator
self.by_profile.count
# plus all the projects where the user is part of a project team
end
当我保存它并尝试在视图中使用它时:
<%= @project.project_counter %>
我收到一条错误消息:
undefined method `by_profile' for #<Project:0x007f98f1dff278>
Did you mean? profile
谁能看到我做错了什么?
【问题讨论】:
-
你打电话给
self.by_profile.count没有通过profile_id试试self.by_profile(<user id here>.count -
我想统计属于用户个人资料的项目数。我真的应该为此添加 user_id 吗?用户与项目没有直接关联。我正在尝试计算项目表中的 profile_ids。
-
“在我的项目模型中,我有一个按 profile_id 查找项目的范围。”你不应该需要那个......这就是协会给你的。如果您想知道给定配置文件的项目数量,请执行以下操作:
Profile.find(profile_id).projects.count -
@TarynEast - 我不知道如何从项目视图中启动它。无论如何感谢您的建议。我找到了一种行之有效的方法,现在就足够了。
-
我不确定我是否理解您所说的“从视图中启动它”是什么意思?您只需复制上面的代码,它应该可以正常工作...?是否在项目视图中并不重要
标签: ruby-on-rails methods count counter