我按照here中的步骤设置用户模型和公司模型之间的收藏关系。具体而言,用户可以拥有许多喜爱的公司。还有一个用户在创建时与公司绑定的功能。
所以这是我当前的模型/ routes / db schema
模型
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
数据库架构
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
(用户是已创建的用户)时。我收到以下错误。
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?
在这种情况下,建议的修复似乎不是正确的做法,我不能为我的生活弄清楚出了什么问题。
答案 0 :(得分:2)
在User
模型中,更改此行:
has_many :favorites, through: :favorite_companies
到此:
has_many :favorites, through: :favorite_companies, source: :company
您在Company
模型:favorited_by
中使用了正确的语法。