railsのAPIモードで、ID以外のカラムで削除したい。

前提

railsのAPIモードです。
dbのレコードをidで削除する方法はわかるのですが、id以外のカラムの条件を付けて削除したい場合、どうしたらいいでしょうか?

実現したいこと

railsで下記のSQL文を実行する。

delete from sample where user_id=1 and post_id=1;

発生している問題・エラーメッセージ

エラーメッセージ

該当のソースコード

sample_controller

1class SampleController < ApplicationController 2 before_action :set_param, only: %i[destroy] 3 4 def destroy 5 if @sample.destroy 6 render json: @sample 7 else 8 render json: @sample.errors 9 end 10 end 11 12 private 13 14 def set_param 15 @sample = Sample.find_by(user_id: params[:id], post_id: params[:id]) 16 end 17 18end

route.rb

1Rails.application.routes.draw do 2 #mount_devise_token_auth_for ‘User’, at: ‘auth’ 3 # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html 4 #root to: ‘posts#index’ 5 6 resources :samples 7 8 delete ‘samples/delete/:user_id/:post_id’, to:‘samples#destroy’ 9 10end

これだとエラーが出て失敗します。

`undefined method `destroy' for nil:NilClass`

試したこと

名前を変えればよいと思い、一度名前をdestroy=>deleteにしても変化がなかったです。
調べても情報がありません。idでの削除しかできない仕様なんでしょうか?

補足情報(FW/ツールのバージョンなど)

なお、user_idとpost_idの組み合合わせが一致するレコードは1しかありません。

コメントを投稿

0 コメント