2015-11-08 48 views
0

我试图添加一个删除按钮,允许用户删除已创建的列表中的电影,但实际上并没有能够从网站上删除电影。如何在没有从网站上实际删除项目的情况下删除项目(例如从愿望清单中删除产品)

这是我在我的列表显示页面

<%= link_to 'Destroy', @list, method: :destroy, data: { confirm: 'Are you sure?' } %> 

明显@list破坏了整个列表,我不希望出现这种情况。我希望他们可以选择删除整个列表,但我也希望他们可以选择删除列表中的项目。

在我的名单控制器

我只有

def destroy 
@list.destroy 
respond_to do |format| 
format.html { redirect_to lists_url, notice: 'List was successfully destroyed.' } 
format.json { head :no_content } 
end 
end 

,并在我的电影控制器。我除了

@movie.destroy 

同样的事情,我想

<%= link_to 'Destroy', @list[:movie_id], method: :destroy, data: { confirm: 'Are you sure?' } %> 

但只给了我一个路由错误,因为我正在调用实际的电影ID,我只想要列表项的ID。

在我routes.db我有这个

Rails.application.routes.draw do 
devise_for :users 
resources :lists 
resources :users, only: [:show, :edit, :update] 
resources :movies, except: [:index] do 
    member do 
    put "like", to: "movies#upvote" 
    put "dislike", to: "movies#downvote" 
end 
end 
get "discover", to: "movies#index" 
get "movies", to: "movies#films" 
get "tv_shows", to: "movies#tv_shows" 
resources :users, only: [:index, :show] 
resources :comments, only: [:create, :destroy] 

devise_scope :user do 
authenticated :user do 
    root 'movies#films', as: :authenticated_root 
    end 
end 
+0

http://guides.rubyonrails.org/ association_basics.html#has-many-association-reference –

回答

0

您需要第三个模型,电影和列表之间的关联,因为这是一个多一对多的关系。这里是如何的模型中的关系可能看起来:

class List < ActiveRecord::Base 
    has_many :list_movies 
    has_many :movies, through: :list_movies 
end 

class ListMovie < ActiveRecord::Base 
    belongs_to :list 
    belongs_to :movie 
end 

class Movie < ActiveRecord::Base 
    has_many :list_movies 
    has_many :lists, through: :list_movies 
end 

而这次移植到添加列表和电影之间的连接表:

有了正确建立的结构,你就可以添加和删除电影来自用户的列表,因为它们被引用为list_movies。 list_movie只是将特定电影与特定列表相关联。只有list_movie记录实际上会在更改列表时添加或删除,而不是实际的电影记录。

如果你想删除一个实际的电影,并且你希望用户列表中该电影的所有实例也被删除,你可能需要在模型中添加依赖的destroy,即“dependent::destroy”列表:

class List < ActiveRecord::Base 
    has_many :movies, through: :list_movies, dependent: :destroy 
end 
class Movie < ActiveRecord::Base 
    has_many :lists, through: :list_movies, dependent: :destroy 
end 

然后添加适当的路线。

最后,在你看来,你将能够做这样的事情:

<% @list.movies.each do |movie| %> 
    <h3><%= movie.title %></h3> 
    <%= link_to 'Destroy', movie, method: :delete, data: { confirm: 'Are you sure?' } %> 
<% end %> 

关于Rails的协会的更多信息,请访问:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

+0

我做了所有必要的更改,但我坚持在我的视图文件夹中,因为我已经有一个每个循环做其他事情,我不知道如何添加另一个我的每个循环看起来像这样 <%@ list.user.find_up_voted_items.each do | movie | %> – begwebdev

+0

该列表属于该用户,对吗?如果是这样,List模型应该“belongs_to:user”。然后你可以有@ list.up_voted_items。 您可能需要在模型上修改“up_voted_items”的方法定义,以便完成您想要的操作。我假设它只是在当前列表上返回最新投票项目,现在将成为list_movies。您可能还需要向list_movies添加一列用于投票计数。 –