Rails,在两个模型之间设置collections夹

我按照这里的步骤设置用户模型和公司模型之间的collections夹关系。 具体而言,用户可以拥有许多喜欢的公司。 还有一个用户在创建时绑定到公司的function。

所以这是我当前的模型/路由/数据库架构

楷模

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 

路线 (可能不适用)

 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 

现在,当我尝试在rails控制台中访问命令user.favorites (其中user是已创建的用户)时。 我收到以下错误。

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

在这种情况下,建议的修复似乎不是正确的做法,我不能为我的生活弄清楚出了什么问题。

在您的User模型中,更改以下行:

 has_many :favorites, through: :favorite_companies 

对此:

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

您在Company模型中使用了正确的语法:favorited_by