我遵循here的步骤来设置用户模型和公司模型之间的收藏夹关系。具体而言,用户可以拥有许多喜爱的公司。还有一种用户在创建时与公司挂钩的功能。Rails,在两个模型之间设置收藏夹
因此,这里有我的电流模式/路由/ DB模式
模式
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模式
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?
在这种情况下,建议的修复似乎不是正确的做法,我不能为我的生活找出问题所在。
在Rails 4中,您还可以使用'patch'请求:'patch:favorite,on :: member'。现在一切正常吗? –
雅,我在@ JKen13579的帮助下得到了所有的工作,但我真的很感激你花时间来看看。 – Scalahansolo