Я новичок в Rails и в настоящее время работаю над своим проектом. Идея состоит в том, что когда пользователь покупает что-то для кого-то, он может создать транзакцию с такой информацией, как мы: для кого он купил, сколько он потратил и, наконец, короткий описание перевода. Я создал столбец администратора в базе данных «Пользователи» и инициализировал пользователя-администратора. Я ограничил доступ к действию index только для администратора - администратор работает нормально. Я хочу, чтобы администратор мог уничтожать транзакции, перечисленные в представлении индекса. То, что я написал для достижения этого, не работает. Вот скриншот представления индекса: https://i.stack.imgur.com/pK1Rg.png
Мой код в представлениях/транзакциях/индексе
<ul>
<% @transactions.each do |transaction| %>
<li>
<%= transaction.user_id %> |
<%= transaction.borrower_name %> |
<%= transaction.value %>
<%= button_to "Delete", action: "destroy", method: :delete,
params: { transaction: { transaction_id: transaction.id } } %>
</li>
<% end %>
</ul>
Мои маршруты
Rails.application.routes.draw do
root 'static_pages#home'
get '/about', to: 'static_pages#about'
get '/help', to: 'static_pages#help'
get '/contact', to: 'static_pages#contact'
get '/signup', to: 'users#new'
get '/login', to: 'session#new'
post '/login', to: 'session#create'
delete '/logout', to: 'session#destroy'
get '/transactions', to: 'transactions#index'
post '/transactions/new', to: 'transactions#create'
get '/transactions/new', to: 'transactions#new'
post '/transactions/:id', to: 'transactions#edit'
delete '/transactions', to: 'transactions#destroy'
resources :users
resources :transactions
end
Мой контроллер
class TransactionsController < ApplicationController
#skip_before_action :is_logged_in?, only: [:index]
#before index and destroy action run check_admin -> ensure access only for admin user
before_action :check_admin?, only: [ :index, :destroy ]
def new
@transaction = Transaction.new
end
def create
#current_user
@transaction = current_user.transactions.build(transaction_params)
#check if borrower_name exists in db - it must exists to make a transaction
check = User.find_by(name: params[:transaction][:borrower_name])
if check != current_user
@transaction.save
flash[:success] = "You have made a transaction!"
redirect_to root_path
elsif check == current_user
flash[:danger] = "You try to make a transaction for yourself!"
render 'transactions/new'
else
flash[:danger] = "Something went wrong!Probably, the borrower is not registed."
render 'transactions/new'
end
end
def index
@transactions = Transaction.all
end
def edit
#get transactions where current_user borrows money from someone
@transaction = Transaction.where(id: params[:transaction][:transaction_id])
if params[:transaction][:active]
@transaction.update(active: params[:transaction][:active], activated_at: Time.zone.now)
else
@transaction.update(active: params[:transaction][:active])
end
redirect_to transaction_path(current_user)
end
def show
#grab the transactions assosiated with the user -
#user lends money - passive transactions
if current_user
#current_user lends money
@lend_transaction = current_user.transactions
#current_user borrows money
@borrow_transaction = Transaction.where(borrower_name: current_user.name)
end
end
def destroy
@transaction = Transaction.find(params[:transaction][:transaction_id])
@transaction.destroy
flash[:success] = "Transaction has been removed!"
redirect_to transactions_path
end
private
def transaction_params
params.require(:transaction).permit(:borrower_name, :value)
end
def check_admin?
#check if current_user has admin => true
redirect_to root_url unless current_user.admin
end
end
Когда я нажимаю «Удалить», вот что происходит в журналах: https://i.stack.imgur.com/A1HU8.png Меня перенаправляют на root_path — странно, посмотрите на действие create. Я не понимаю, почему он говорит о недопустимом параметре: :transaction_id. Я тоже не понимаю, почему после нажатия на Удалить мелькает сообщение: Вы совершили транзакцию! происходит. Такая вспышка должна происходить при создании действия. Вот html:
Буду признателен за любую помощь.
Вот часть кода helpers/session_helper, связанная с current_user:
#method to determine a current user
module SessionHelper
def current_user
#if there is a session -> use session hash
if session[:user_id]
#nil or equal
@current_user ||= User.find_by(id: session[:user_id])
#if there are cookies -> use cookies to operate log in
elsif cookies.encrypted[:user_id]
#find the user by the encrypted user_id key
user = User.find_by(id: cookies.encrypted[:user_id])
#if user exists and the remember token authentication succeed
#log in and set @current_user to user
if user && user.authenticated?(cookies[:remember_token])
log_in(user)
@curent_user = user
end
end
end