Question

I followed the steps from here to setup a favorites relationship between a user model and a company model. Specifically, a user can have many favorite companies. There is also a functionality of a user being tied to a company on creation.

So here are my current models/routes/db schema

Models

class FavoriteCompany < ActiveRecord::Base
    belongs_to :company
    belongs_to :user
...

class User < ActiveRecord::Base

  has_many :companies

  has_many :favorite_companies
  has_many :favorites, through: :favorite_companies
...

class Company < ActiveRecord::Base

    belongs_to :user

    has_many :favorite_companies
    has_many :favorited_by, through: :favorite_companies, source: :user

Routes (May not be applicable)

resources :companies do
  put :favorite, on: :member
end

DB Schema

ActiveRecord::Schema.define(version: 20140429010557) do

  create_table "companies", force: true do |t|
    t.string   "name"
    t.string   "address"
    t.string   "website"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.float    "latitude"
    t.float    "longitude"
    t.text     "popup",         limit: 255
    t.text     "description",   limit: 255
    t.string   "primary_field"
    t.string   "size"
    t.integer  "user_id"
  end

  create_table "favorite_companies", force: true do |t|
    t.integer  "company_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.string   "remember_token"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["remember_token"], name: "index_users_on_remember_token"

end

Now when I try to access the command user.favorites (Where user is an already created user) within the rails console. I get the following error.

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :favorite or :favorites in model FavoriteCompany. 
Try 'has_many :favorites, :through => :favorite_companies, :source => <name>'. Is it one of :company or :user?

The suggested fix doesn't seem like the right thing to do in this case, and I can't for the life of me figure out what is going wrong.

Was it helpful?

Solution

In your User model, change this line from:

has_many :favorites, through: :favorite_companies

to this:

has_many :favorites, through: :favorite_companies, source: :company

You used the correct syntax in your Company model for :favorited_by.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top