我正在做一个待办事项清单,在这里我可以有多个执行不同任务的清单。我的主要问题是当我尝试创建收藏夹功能时,可以在其中将列表添加到收藏夹列表中。
列表模型
class List < ApplicationRecord
belongs_to :user
has_many :tasks
has_many :favorites
has_many :favoriters, through: :favorites, foreign_key: :user_id
accepts_nested_attributes_for :tasks, allow_destroy: true
end
收藏夹模型
class Favorite < ApplicationRecord
belongs_to :list
belongs_to :user
end
用户模型
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :lists
has_many :favorites
has_many :favorite_lists, through: :favorites
end
列表控制器:
def favorites
@list = List.find(params[:list_id])
current_user.favorites << @list
redirect_to lists_path, notice: 'Added to Favorite List'
end
路线:
resources :lists do
resources :tasks, only: [:index, :new, :create]
post :favorites
end
在我的节目列表视图中的链接:
<%= link_to "Favorite", list_favorites_path(@list), method: :post %>
消息错误:
Favorite(#70365311619800) expected, got #<List id: 1, user_id: 1, public: true, created_at: "2019-05-02 00:43:05", updated_at: "2019-05-02 00:43:05", title: "teste", favorite: nil> which is an instance of List(#70365317909860)
我在这里想念什么?
答案 0 :(得分:0)
我相信这里:
def favorites
@list = List.find(params[:list_id])
current_user.favorites << @list
redirect_to lists_path, notice: 'Added to Favorite List'
end
您想要的:
def favorites
@list = List.find(params[:list_id])
current_user.favorite_lists << @list
redirect_to lists_path, notice: 'Added to Favorite List'
end
我相信您也必须在此处更改has_many :favorite_lists, through: :favorites
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :lists
has_many :favorites
has_many :favorite_lists, through: :favorites
end
因为Favorite
没有favorite_list_id
,所以它有list_id
。像这样:
has_many :favorite_lists, through: :favorites, source: :list