首页 > 解决方案 > 如何用值破坏模型

问题描述

我对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

标签: ruby-on-rails

解决方案


它有时会删除,但大多数时候我都会收到此错误

如果它“有时”有效,那么我的猜测是您在删除后没有重新呈现您的页面,并且您最终可能会在同一记录上单击两次“取消关注”按钮,这将引发RecordNotFound像您显示的错误。

您的 html 重定向看起来不错,但请确保您在请求为 json 格式时也刷新页面。


推荐阅读