skip to Main Content

Please understand that I am not familiar with English.

I am creating a sample application with Rails.
For some reason the following error occurs when I press the delete button on a micropost.
error

First, paste the route file.

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


Next is the post management page for microposts, including a delete button.

_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>

A micropost controller containing a destroy method.

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

models

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

I found a similar question on this site.
The answer is "There is a flaw in JS. Please add this to your Gemfile or js file".

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 file.

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.*

I followed this but the error did not go away.

I don’t think the settings for routing, controllers, links, etc. are correct,
but are there any flaws?
Or is it still j Query?
By the way, I understand the grammar of javascript, but I’m an amateur.

Thank you for reading this far.
If you have any ideas, please comment or answer.

3

Answers


  1. can you try

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

    Otherwhise you should look this SO Rails' link_to method: GETing when it should DELETE

    Login or Signup to reply.
  2. If you are using Rails 7+, the preferred way is to use a button:

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

    It will render an HTML form which sends a POST request with a hidden _method attribute with ‘delete’ value. Rails will treat this as if it has a DELETE method. And there is no need to use Rails UJS or jQuery.

    NOTE Do not use this one within another form (HTML forbids one form inside another).

    Login or Signup to reply.
  3. Rails dropped the jquery_rails gem way back when Rails 5.1 came out in 2017. It has no place in modern applications. It was replaced by rails_ujs which had the same functionality minus the jQuery dependency up until Rails 7.

    Rails 7 replaces both rails_ujs and Turbolinks with
    Turbo. Turbo provides the same functionality as rails_ujs but the data attribute that the event handler attaches itself to is named data-turbo-method instead of data-method.

    You’re actually doing it correctly here even if the idiomatically correct call is:

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

    You can also use button_to which works even without JS:

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

    So why isn’t it working?

    There could be a lot of different reasons.

    • Turbo isn’t loaded on the page.
    • A script error is preventing Turbo from working.
    • There is a conflicting event handler on the page that is breaking the functionality provided by Turbo.
    • […]

    Any of these will lead to the link doing what links naturally do and a GET request will be sent instead. Checking the browser console is your first step in debugging this.

    See:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search