您好,我正在尝试在我的应用中创建书签功能。我已经创建了 我要添加书签的模型(发型),我还有一个用户模型和一个“ Saved_Hairstyle”模型,这是方案中的联接表。 在我的routes.rb文件中,添加了一条创建和删除路由。在我的控制器中,我写出了CREATE&DELETE方法。然后,我继续在视图中将link_to到我的CREATE&DELETE方法路径。
我希望当我单击CREATE Link时,会触发POST方法,以便我可以在页面上显示某个元素为“已添加书签”,并且当我单击DELETE链接时,会触发一个DELETE方法,以便在页面上将元素显示为“未标记”,但它们不起作用。 当我在Rails C中进行RAILS ROUTES时,我可以看到正确的路径,但是当我单击链接时却什么也没做。 回购以便于理解:https://github.com/Angela-Inniss/hair-do
routes.rb
Rails.application.routes.draw do
root to: 'pages#home'
devise_for :users
resources :hairstyles do
member do
put "like", to: "hairstyles#upvote"
put "dislike", to: "hairstyles#downvote"
end
resources :comments, only: :create
resources :saved_hairstyles, only: [:new,:create]
end
resources :saved_hairstyles, only: :destroy
resources :comments, only: :destroy
resources :hairdressers
end
class SavedHairstylesController < ApplicationController
def create
@hairstyle = Hairstyle.find(params[:hairstyle_id])
@saved_hairstyle = SavedHairstyle.new(user: current_user, hairstyle: @hairstyle)
if @saved_hairstyle.save
respond_to do |format|
format.html { redirect_to hairstyle_path(@saved_hairstyle.hairstyle) }
format.js # <-- will render `app/views/comments/create.js.erb`
end
else
respond_to do |format|
format.html { render 'hairstyles' }
format.js # <-- idem
end
end
end
end
def destroy
@saved_hairstyle = SavedHairstyle.find(params[:id])
@saved_hairstyle.destroy
@hairstyle = @saved_hairstyle.hairstyle
respond_to do |format|
format.html { redirect_to hairstyle_path(@saved_hairstyle.hairstyle }
format.js
end
end
view.html.erb
<div class="bookmark">
<% saved_hairstyle = SavedHairstyle.find_by(user: current_user, hairstyle: hairstyle.id) %>
<% if saved_hairstyle %>
<%= link_to hairstyle_saved_hairstyle_path(saved_hairstyle), method: :post do %>
<i class="fas fa-plus"></i>
<% end %>
<% else %>
<%= link_to saved_hairstyle_path(hairstyle), method: :delete do %>
<i class="fas fa-plus-circle"></i>
<% end %>
<% end %>
</div>
create.js.erb文件(这是我想在POST请求中发生的事情(我对DELETE请求有类似的要求)
plusCircle = document.getElementById("bookmark");
plusCircle.innerHTML = `<%= link_to '#', method: :post do %>
<i class="fas fa-plus"></i>
<% end %>`
答案 0 :(得分:2)
您的视图逻辑中似乎存在一些错误。您正在加载已保存的发型,然后尝试再次对其进行标记。您还尝试删除已保存的发型(如果不存在)。路径助手也似乎是错误的(删除方法不是嵌套的,嵌套的资源应为复数)。也许看起来应该像这样:
<div class="bookmark">
<% saved_hairstyle = SavedHairstyle.find_by(user: current_user, hairstyle: hairstyle.id) %>
<% if saved_hairstyle %>
<%= link_to saved_hairstyle_path(saved_hairstyle), method: :delete do %>
<i class="fas fa-plus-circle"></i>
<% end %>
<% else %>
<%= link_to hairstyle_saved_hairstyles_path(hairstyle), method: :post do %>
<i class="fas fa-plus"></i>
<% end %>
<% end %>
</div>
顺便说一句,如果您检查控制台,则可能会看到一些错误,这些错误会指引您正确的方向。您还应该将saved_hairstyle查询移动到辅助方法。