[英]Button from view to call a controller action to update database column
我試圖在單擊按鈕時將用戶添加到表列(PostgreSQL)的數組中。 單擊按鈕注冊,但未調用控制器方法,並且未給出錯誤。
我有以下帶有按鈕的視圖。
views / users / index.html.erb
<%= form_for(Pairing.new, url: users_path, method: :patch, html: { id: 'my_special_form' }) do |f| %>
<div class="field">
<%= f.label :supervisor_id %>
<%= f.collection_select(:supervisor_id, User.where(role: 1), :id, :name) %>
</div>
<div class="field">
<%= f.label :student_id %>
<%= f.collection_select(:student_id, User.where(role: 0), :id, :name) %>
</div>
<%= f.submit %>
<% end %>
然后將javascript放在另一個文件中。
資產/javascripts/pair.js
$("#my_special_form").submit(function(){
var url = this.action + "/" + this.elements["pairing[student_id]"].value;
$.ajax(url, {
beforeSend: $.rails.CSRFProtection,
data: {
user: {
supervisor_id: this.elements["pairing[supervisor_id]"].value
}
}
type: 'PATCH',
dataType: 'JSON',
success: function(data, textStatus, jqXHR) {
console.log('Success', data, textStatus, jqXHR);
}
});
return false; // cancels out the normal form submission
});
我正在嘗試在控制器中調用此方法
控制器/用戶控制器
class UsersController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
def index
@users = User.all
authorize User
end
def show
@user = User.find(params[:id])
authorize @user
end
def update
@user = User.find(params[:id])
authorize @user
if @user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
authorize user
user.destroy
redirect_to users_path, :notice => "User deleted."
end
def pair
supervisor = User.find(params[:id1])
student = User.find(params[:id2])
studentlist = supervisor.select(:supervised_students)
studentlist << student.
supervisor.update_attribute(:supervised_students => studentlist)
@supervisor.save
end
private
def secure_params
params.require(:user).permit(:role)
end
end
add_supervisor遷移
class AddSupervisor < ActiveRecord::Migration
def change
add_column :users, :supervisor_id, :integer
end
end
用戶模型
enum role: [:student, :supervisor, :admin]
after_initialize :set_default_role, :if => :new_record?
has_many :students, class_name: "Users",
foreign_key: "supervisor_id"
belongs_to :supervisor, class_name: "User"
def set_default_role
self.role ||= :student
end
Routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users
resources :pairings
resources :conversations, only: [:index, :show, :destroy] do
member do
post :reply
end
end
resources :conversations, only: [:index, :show, :destroy] do
member do
post :restore
end
end
resources :conversations, only: [:index, :show, :destroy] do
collection do
delete :empty_trash
end
end
resources :conversations, only: [:index, :show, :destroy] do
member do
post :mark_as_read
end
end
resources :messages, only: [:new, :create]
devise_scope :user do
authenticated :user do
root 'pages#index', as: :authenticated_root
end
unauthenticated do
root 'pages#welcome', as: :unauthenticated_root
end
end
root to: 'pages#index'
end
URI中的#
用於片段標識符-根據規范,它對服務器是透明的。
因此,當您發送ajax請求時,其實際解釋為POST /users
。
root
用於設置/
路徑的處理程序。 如果要添加POST users/pair
,則可以這樣做
resources :users do
collection do
post 'pair', to: "users#pair"
end
end
請注意,路由中的#
表示controller#action
#action,與結果無關
但是,這就是我要解決的問題。
確保您在users
上具有supervisor_id
列。
class User < ActiveRecord::Base
has_many :students, class_name: "Users",
foreign_key: "supervisor_id"
belongs_to :supervisor, class_name: "User"
end
在這種情況下,您可能要考慮是否真的需要一條特殊的路線。 特別是因為您正在使用ajax。
實際上,如果您想指派一名學生擔任主管,那么您真正需要的只是PATCH請求。
PATCH /users/5 { supervisor_id: 6 }
如果您僅列出學生的位置,則可以使用如下所示的簡單表格,您會很方便:
<%= form_for(user) do |f| %>
<%= f.collection_select :supervisor, User.where(role: 1) %>
<%= f.submit %>
<% end %>
但是,如果要選擇兩個,則需要動態設置ajax請求URL。 我們將使用一些技巧來正確使用表單助手:
# app/models/pairing
class Pairing
include ActiveModel::Model
attr_accessor :supervisor_id, :student_id
end
這是一個沒有數據庫表支持的模型。 我們可以簡單地使用它來綁定表單輸入:
<%= form_for(Pairing.new, url: users_path, method: :patch, html: { id: 'my_special_form' }) do |f| %>
<div class="field">
<%= f.label :supervisor_id %>
<%= f.collection_select(:supervisor_id, User.where(role: 1), :id, :name) %>
</div>
<div class="field">
<%= f.label :supervisor_id %>
<%= f.collection_select(:student_id, User.where(role: 0), :id, :name) %>
</div>
<%= f.submit %>
<% end %>
這種形式不會奏效,因為它將修補到/users
。 我們想要做的就是在提交表單時更改URL以指向當前用戶。
$("#my_special_form").submit(function(){
var url = this.action + "/" + this.elements["pairing[student_id]"].value;
$.ajax(url, {
beforeSend: $.rails.CSRFProtection,
data: {
user: {
supervisor_id: this.elements["pairing[supervisor_id]"].value
}
},
type: 'PATCH',
dataType: 'JSON',
success: function(data, textStatus, jqXHR) {
console.log('Success', data, textStatus, jqXHR);
}
});
return false; // cancels out the normal form submission
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.