ruby-on-rails 删除微帖子时出错,由于某种原因,为https请求了GET方法

pkbketx9  于 2023-02-26  发布在  Ruby
关注(0)|答案(3)|浏览(149)

请理解我不熟悉英语。
我正在用Rails创建一个示例应用程序。由于某种原因,当我按下micropost上的delete按钮时,出现了以下错误。error
首先,粘贴管线文件。

config/routes.rb

Rails.application.routes.draw do
  root "static_pages#home"
  get '/help', to: "static_pages#help"
  get '/search', to: 'searchs#search'
  get '/signup', to: 'users#new'
  get    "/login",   to: "sessions#new"
  post   "/login",   to: "sessions#create"
  delete "/logout",  to: "sessions#destroy"
  get '/diary',  to: "static_pages#diary"
  resources :users
  resources :microposts,          only: [:create, :destroy]
end

接下来是微帖的帖子管理页面,包括一个删除按钮。

_microposts.html.erb

<li id="micropost-<%= micropost.id %>">
  <%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
  <span class="user">
   <%= link_to micropost.user.name, micropost.user %>
  </span>
  <span class="content">
   <%= micropost.content %>
   <% if micropost.image.attached? %>
      <%= image_tag micropost.image.variant(:display) %>
   <% end %>
  </span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(micropost.created_at) %> ago.
    <% if current_user?(micropost.user) %>
      <%= link_to "delete", micropost, data: { "turbo-method": :delete,
                                                turbo_confirm: "You sure?" } %>
    <% end %>
  </span>
</li>

一种包含销毁方法的微柱控制器。

app/controllers/micropost_controller.rb

class MicropostsController < ApplicationController

    before_action :logged_in_user, only: [:create, :destroy]
        before_action :correct_user,   only: :destroy

    def create
     @micropost = current_user.microposts.build(micropost_params)
         @micropost.image.attach(params[:micropost][:image])
          if @micropost.save
           flash[:success] = "Micropost created!"
           redirect_to diary_path
          else
           @feed_items = current_user.feed.paginate(page: params[:page])
           render 'static_pages/home', status: :unprocessable_entity
          end
    end
  
       def destroy
         @micropost.destroy
         flash[:success] = "Micropost deleted"
        if request.referrer.nil?
         redirect_to root_url, status: :see_other
        else
         redirect_to request.referrer, status: :see_other
        end
       end
    
     private

    def micropost_params
      params.require(:micropost).permit(:content, :image)
    end

    def correct_user
      @micropost = current_user.microposts.find_by(id: params[:id])
      redirect_to root_url, status: :see_other if @micropost.nil?
    end
  end

模型

app/models/micropost.rb

class Micropost < ApplicationRecord
  belongs_to :user
  has_one_attached :image do |attachable|
    attachable.variant :display, resize_to_limit: [500, 500]
  end
  default_scope -> { order(created_at: :desc) }
  validates :user_id, presence: true
  validates :content, presence: true, length: { maximum: 140 }
  validates :image,   content_type: { in: %w[image/jpeg image/gif image/png],
                                    message: "must be a valid image format" },
                                    size:         { less_than: 5.megabytes,
                                    message:   "should be less than 5MB" }
end

我在这个网站上发现了一个类似的问题,答案是“JS有缺陷,请将此添加到您的Gemfile或JS文件中”。

Gemfile

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

gem "rails",                      "7.0.4"
gem "ransack"
gem "image_processing",           "1.12.2"
gem 'jquery-rails'                         < add this.
gem 'turbolinks'                           < add this.
gem "active_storage_validations", "0.9.8"
gem "bcrypt",                     "3.1.18"
gem "faker",                      "2.21.0"
gem "will_paginate",              "3.3.1"
gem "bootstrap-will_paginate",    "1.0.0"
gem "bootstrap-sass",             "3.4.1"
gem "sassc-rails",                "2.1.2"
gem "sprockets-rails",            "3.4.2"
gem "importmap-rails",            "1.1.0"
gem "turbo-rails",                "1.1.1"
gem "stimulus-rails",             "1.0.4"
gem "jbuilder",                   "2.11.5"
gem "puma",                       "5.6.4"
gem "bootsnap",                   "1.12.0", require: false

group :development, :test do
  gem "sqlite3", "1.4.2"
  gem "debug",   "1.5.0", platforms: %i[ mri mingw x64_mingw ]
  gem 'guard-rspec', require: false
  gem 'factory_bot_rails'
end

group :development do
  gem "web-console", "4.2.0"
end

group :test do
  gem "capybara",                 "3.37.1"
  gem "selenium-webdriver",       "4.2.0"
  gem "webdrivers",               "5.2.0"
  gem "rails-controller-testing", "1.0.5"
  gem "minitest",                 "5.15.0"
  gem "minitest-reporters",       "1.5.0"
  gem "guard",                    "2.18.0"
  gem "guard-minitest",           "2.4.6"
  gem 'rspec-rails'
  gem 'spring-commands-rspec'
  gem 'factory_bot_rails'
  gem 'database_cleaner'
  gem 'launchy'
end

group :production do
  gem "pg",         "1.3.5"
  gem "aws-sdk-s3", "1.114.0", require: false
end

# gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem "erb-formatter", "~> 0.4.1"

gem "dockerfile-rails", ">= 1.0", :group => :development

js文件。

app/assets/config/manifest.js

//= link_tree ../images
//= link_directory ../stylesheets .css
//= link_tree ../../javascript .js
//= link_tree ../../../vendor/javascript .js

//= require jquery      *< add this.*
//= require jquery_ujs  *< add this.*

我遵循了这一点,但错误并没有消失。
我觉得路由、控制器、链接等设置不对,但有没有瑕疵?还是j Query?顺便说一句,我懂javascript的语法,但我是个业余爱好者。
谢谢你阅读到这里,如果你有任何想法,请评论或回答。

oyxsuwqo

oyxsuwqo1#

早在2017年Rails 5.1发布时,Rails就放弃了jquery_rails gem,它在现代应用程序中没有位置,被rails_ujs取代,rails_ujs具有相同的功能,但在Rails 7之前不依赖jQuery。
Rails 7将rails_ujs和Turbolinks替换为Turbo。Turbo提供了与rails_ujs相同的功能,但事件处理程序将其自身附加到的数据属性命名为data-turbo-method,而不是data-method
实际上,您在这里做得很正确,即使习惯用法正确的调用是:

<%= link_to "delete", micropost, data: { turbo_method: :delete, turbo_confirm: "You sure?" } %>

您也可以使用button_to,它甚至可以在没有JS的情况下工作:

<%= button_to "delete", micropost, method: :delete, data: { turbo_confirm: "You sure?" } %>

那么,为什么它不起作用呢?

可能有很多不同的原因。

  • Turbo未加载到页面上。
  • 脚本错误导致Turbo无法工作。
  • 页面上存在冲突的事件处理程序,该事件处理程序破坏了Turbo提供的功能。
  • [...]

任何一种情况都会导致链接做链接自然会做的事情,而GET请求会被发送。检查浏览器控制台是调试的第一步。
参见:

  • https://guides.rubyonrails.org/working_with_javascript_in_rails.html#replacements-for-rails-ujs-functionality
  • https://turbo.hotwired.dev/handbook/drive#performing-visits-with-a-different-method
dauxcl2d

dauxcl2d2#

如果您使用的是Rails 7+,首选方法是使用按钮:

<%= button_to "delete", micropost, method: :delete %>

它将呈现一个HTML表单,该表单发送一个POST请求,该请求带有一个隐藏的_method属性,该属性的值为“delete”。Rails会将其视为具有DELETE方法。并且不需要使用Rails UJS或jQuery。

注意不要在另一个表单中使用此表单(HTML禁止在另一个表单中使用一个表单)。

nwlqm0z1

nwlqm0z13#

你能不能试

<%= link_to 'delete', YOUR_PATH, method: :delete %>

否则你应该看起来像这样Rails' link_to method: GETing when it should DELETE

相关问题