다음과 같은 사용자 및 페어링 모델이 있습니다.
class User < ActiveRecord::Base
enum role: [:student, :supervisor, :admin]
has_many :students, class_name: "User",
foreign_key: "supervisor_id"
belongs_to :supervisor, class_name: "User"
has_and_belongs_to_many :pairings
end
class Pairing < ActiveRecord::Base
has_and_belongs_to_many :supervisor, class_name: 'User'
belongs_to :student, class_name: 'User'
end
그리고 스키마의 관련 부분 (크기에 대한 devise 필드 제거) :
ActiveRecord::Schema.define(version: 20160221222318) do
create_table "pairings", force: :cascade do |t|
t.integer "supervisor_id"
t.integer "student_id"
t.string "project_title"
end
add_index "pairings", ["student_id"], name: "index_pairings_on_student_id", unique: true
add_index "pairings", ["supervisor_id"], name: "index_pairings_on_supervisor_id"
create_table "users", force: :cascade do |t|
t.string "name"
t.integer "role"
t.integer "supervisor_id"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
end
모든 학생을 나열하는 드롭 다운 상자 1 개와 모든 감독자를 나열하는 1 개의 양식이있는보기가 있습니다. 내 목표는 두 가지입니다.
(1) 상자에서 감독자와 학생이 선택되면 해당 ID를 얻고 감독자의 ID를 학생의 supervisor_id 열에 할당합니다. (AJAX 패치 요청 사용)
(2) 드롭 다운의 ID로 페어링 테이블에 새 행을 만듭니다. (pairings_controllers create 메소드를 통해 수행)
이것이 내 견해입니다.
<script>
$("#my_special_form").submit(function(){
var url = "/users/" + 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
});
</script>
<%= form_for(Pairing.new, url: pairings_path, method: :post, 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>
<div class ="field">
<%= f.label :project_title %>
<%= f.text_field :project_title %>
<%= f.submit %>
<% end %>
그리고 컨트롤러 :
class PairingsController < ApplicationController
def new
@pairing = Pairing.new
end
def create
@pairing = Pairing.new(pair_params)
end
def update
@pairing = Pairing.find(params[:id])
@pairing.update_attributes(pairing_params)
end
private
def pair_params
params.require(:pairing).permit(:supervisor_id, :student_id, :project_title)
end
end
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
private
def secure_params
params.require(:user).permit(:role, :supervisor_id)
end
end
내가 가진 문제는 스크립트가 성공하지 못했지만 여전히 supervisor_id 필드를 업데이트하는 것입니다. 페어링 테이블 항목이 생성되는지 확인하기 위해 스크립트없이 테스트를 시도했지만 양식의 매개 변수가 수신되었지만 버튼을 누르면 트랜잭션에 커밋되지 않습니다. 무엇을 해야할지 모르겠다 정말 어떤 도움을 주셔서 감사합니다!
다음 변경을 수행하여 해결됨
<%= form_for(Pairing.new, url: new_pairing_path, method: :post, html: { id: 'pairing_form' }) do |f| %>
Routes.rb
match '/pairings/new', to: 'pairings#create', via: [:post]
match '/users/update', to: 'users#update', via: [:patch]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다