0

我目前正試圖在我的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 
+0

你所有的課程都被命名爲'Event'?用戶belongs_to用戶?似乎你在那裏有很多錯別字,請清理你的代碼示例,這是非常混亂的。 –

+1

@thorstenmüller哇。對於那個很抱歉。我非常累,手動輸入一切。我編輯了一切,以反映它應該如何。感謝您的高舉。 – adanot

回答

2
class User < ActiveRecord::Base 
    has_many :favorite_events 
    has_many :events 
    has_many :favorites, through: :favorite_events, source: :event 
end 
1

你的模型結構S應該是這樣的。

event.rb

class Event < ActiveRecord::Base 
    belongs_to :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 

這表明THA t:用戶has_many事件 和用戶has_many favorite_event通過事件。

我認爲你想實現。 我對@adanot?

+0

@adanot它適合你嗎? – sunil

+0

我編輯了我的問題。我最初意外地犯了很多錯誤和錯別字。 – adanot