查找并统计具有 HABTM 关系对象名称的所有配置文件
在我的 Rails 3 应用程序中,我有两个模型:Profile
和 Item
。每个人都与另一个人有 HABTM 关系。在我的 Profile 模型中,我有一个方法 wish_items
来创建同名的数组 (wish_items)。如果某个项目包含“wish”类别,则会将其添加到该配置文件的 wish_items
数组中。
出于此问题的目的,假设我有一个名为“电话”且类别为“愿望”的项目。我想要做的是能够找到并计算 wish_items
数组中包含“phone”的所有配置文件,以便我可以在视图中呈现该计数。我的代码如下。
我的 Profile.rb
模型:
class Profile < ActiveRecord::Base
has_and_belongs_to_many :items
def wish_items
wish_items = Array.new
items.each do |item|
if item.category == "wish"
wish_items << item
end
end
return wish_items
end
end
我的 Item.rb
模型:
class Item < ActiveRecord::Base
has_and_belongs_to_many :profiles
end
我有一个用于此关系的连接表 items_profiles
。这是迁移:
class CreateItemsProfiles < ActiveRecord::Migration
def self.up
create_table :items_profiles, :id =>false do |t|
t.references :item
t.references :profile
end
end
...
end
我看到了这个 上一个问题并尝试回答,但收到错误NameError:未初始化的常量电话
。这是我从中尝试过的代码:
Profile.all(:include => :items, :conditions => ["items.name = ?", phone])
具体来说,我将该代码放在以下位置:
<%= pluralize(Profile.all(:include => :items, :conditions => ["items.name = ?", phone])).count, "person") %>
我怎样才能做到这一点?
In my Rails 3 app I have two models, Profile
and Item
. Each has a HABTM relationship with the other. In my Profile model, I have a method wish_items
that creates an Array of that same name (wish_items). If an item contains the category "wish", it is added to the wish_items
Array for that profile.
For the purpose of this question, say I have an item named "phone" with category "wish". What I'd like to do is be able to find and count all Profiles that have "phone" in their wish_items
Array so I can render that count in a view. My code is below.
My Profile.rb
model:
class Profile < ActiveRecord::Base
has_and_belongs_to_many :items
def wish_items
wish_items = Array.new
items.each do |item|
if item.category == "wish"
wish_items << item
end
end
return wish_items
end
end
My Item.rb
model:
class Item < ActiveRecord::Base
has_and_belongs_to_many :profiles
end
I have a join table items_profiles
for this relationship. Here is that migration:
class CreateItemsProfiles < ActiveRecord::Migration
def self.up
create_table :items_profiles, :id =>false do |t|
t.references :item
t.references :profile
end
end
...
end
I saw this previous question and gave the answer a try but got an error NameError: uninitialized constant phone
. Here is the code I tried from that:
Profile.all(:include => :items, :conditions => ["items.name = ?", phone])
Specifically I put that code in the following:
<%= pluralize(Profile.all(:include => :items, :conditions => ["items.name = ?", phone])).count, "person") %>
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上述失败是因为我的报价中没有电话。简单的。以下有效:
和复数:
The above was failing because I didn't have phone in quotations. Simple. The following worked:
And pluralizing: