我目前正試圖在我的Rails應用程序中實現一個最喜歡的功能。但是,當我嘗試單擊「添加到收藏夾」鏈接時,我收到錯誤消息:Rails有很多通過源協會找不到錯誤
在模型FavoriteEvent中找不到源關聯:收藏夾或:收藏夾。試試'has_many:favorites,:through =>:favorite_events,:source =>'。是以下其中一項:事件還是:用戶?
我嘗試如下:
Event.rb
class Event < ActiveRecord::Base
belongs_to :user
has_many :favorite_events
has_many :favorited_by, through: :favorite_events, source: :user
end
User.rb
class User < ActiveRecord::Base
has_many :events
has_many :favorite_events
has_many :favorites, through: :favorite_events
end
Favorite_event.rb
class FavoriteEvent < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
event_controller
def favorite
type = params[:type]
if type == "add"
current_user.favorites << @event
else
redirect_to :back, notice: 'Event not added'
end
end
查看
<%= link_to "Add to calendar",
favorite_event_path(@event, type: "favorite"),
method: :put %>
路線
resources :events do
put :favorite, on :member
end
你所有的課程都被命名爲'Event'?用戶belongs_to用戶?似乎你在那裏有很多錯別字,請清理你的代碼示例,這是非常混亂的。 –
@thorstenmüller哇。對於那個很抱歉。我非常累,手動輸入一切。我編輯了一切,以反映它應該如何。感謝您的高舉。 – adanot