我目前正在尝试在我的rails应用程序中实现一个喜欢的功能。但是,当我尝试单击添加到收藏夹链接时,我收到错误消息:
无法在模型FavoriteEvent中找到源关联:favorite或:Favorites。试试'has_many:favorites,:through => :favorite_events,:source => ”。它是以下之一:event或:user?
我的尝试如下:
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 :(得分:2)
class User < ActiveRecord::Base
has_many :favorite_events
has_many :events
has_many :favorites, through: :favorite_events, source: :event
end
答案 1 :(得分:1)
你的模型结构应该是这样的。
<强> 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
这表明:用户has_many事件 和一个用户has_many favorite_event通过事件。
我认为你想要实施。 我是对的吗?@adanot?