我遵循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