ruby-on-rails - 如何用值破坏模型
问题描述
我对rails有点陌生。我有一个名为 follow 的模型,它具有值(请求者和追随者)。我无法创建一个按钮来破坏具有两个值的选择模型
<dt>User ID:</dt>
<dd><%= @user.id %></dd>
<dt>User email:</dt>
<dd><%= @user.email %></dd>
<% if Follow.where(:requestor => current_user.id, :following =>@user.id).present? %>
<%= button_to 'Unfollow', follow_url, method: :delete, class: "text-danger", data: { confirm: 'Are you sure?' } %>
<% else %>
<%= button_to "Follow", {:controller => 'follows', :action => 'create', :requestor => current_user.id, :following => @user.id}, {:method => :post} %>
<% end %>
else 语句中下面的 Follow 按钮有效,但我不知道如何让销毁按钮工作。我在用户显示页面上而不是在关注索引上执行这些按钮。
def destroy
@follow.destroy
respond_to do |format|
format.html { redirect_to follows_url, notice: 'Follow was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_follow
@follow = Follow.find(params[:id])
end
# Only allow a list of trusted parameters through.
def follow_params
params.permit(:requestor, :following)
end
def require_permission
if Follow.find(params[:id]).user != current_user
redirect_to goals_url, flash: { error: "You do not have permission to do that."}
end
end
end
我一直找不到“id”错误的关注。它有时会删除,但大多数时候我都会收到此错误。
路线。使用通用格式
require 'sidekiq/web'
Rails.application.routes.draw do
resources :follows
resources :accounts
resources :goals
resources :retirements
get '/users', to: 'users#index'
get '/user/:id', to: 'users#show', as: 'user'
resources :calculate_debts
get '/privacy', to: 'home#privacy'
get '/terms', to: 'home#terms'
authenticate :user, lambda { |u| u.admin? } do
mount Sidekiq::Web => '/sidekiq'
end
resources :notifications, only: [:index]
resources :announcements, only: [:index]
devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
root to: 'home#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
解决方案
它有时会删除,但大多数时候我都会收到此错误
如果它“有时”有效,那么我的猜测是您在删除后没有重新呈现您的页面,并且您最终可能会在同一记录上单击两次“取消关注”按钮,这将引发RecordNotFound
像您显示的错误。
您的 html 重定向看起来不错,但请确保您在请求为 json 格式时也刷新页面。
推荐阅读
- c - 预处理器:错误:在标记“(”之前缺少二元运算符
- azure - Azure LUIS 所有权变更
- c# - Microsoft.Data.SqlClient.SqlException (0x80131904):“,”附近的语法不正确
- python - 如何在 python3.8+ 中自动化对象初始化
- python - 通过列表范围测试失败
- android - 试图让软键盘输入按钮说搜索或显示搜索放大镜并处理其单击 EditText
- sql - Cursorfetch:INTO 列表中声明的变量数量必须与所选列的数量相匹配 [不同重复]
- c# - 添加开关盒
- windows-runtime - Windows PWA 中的 Traceroute
- c# - 如何找到集合的所有分区(C++)