0

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?

Community
  • 1
  • 1
tvalent2
  • 4,959
  • 10
  • 45
  • 87

1 Answers1

0

The above was failing because I didn't have phone in quotations. Simple. The following worked:

Profile.all(:include => :items, :conditions => ["items.name =  ?", "phone"])

And pluralizing:

<%= pluralize(Profile.all(:include => :items, :conditions => ["items.name =  ?", "phone"]).count, "person") %>
tvalent2
  • 4,959
  • 10
  • 45
  • 87