강력한 매개 변수를 사용하여 배열을 허용하는 방법
저는 has_many:through 연결을 사용하는 Rails 3 앱이 있는데, 제가 Rails 4 앱으로 다시 만들기 때문에 Rails 4 버전의 관련 모델에서 ID를 저장할 수 있습니다.
이 세 가지 관련 모델은 두 버전에 대해 동일합니다.
분류.rb
class Categorization < ActiveRecord::Base
belongs_to :question
belongs_to :category
end
질문.rb
has_many :categorizations
has_many :categories, through: :categorizations
카테고리.rb
has_many :categorizations
has_many :questions, through: :categorizations
두 앱 모두에서 카테고리 ID가 다음과 같은 생성 작업으로 전달됩니다.
"question"=>{"question_content"=>"How do you spell car?", "question_details"=>"blah ", "category_ids"=>["", "2"],
Rails 3 앱에서 새 질문을 만들면 질문 테이블에 삽입한 다음 범주화 테이블에 삽입합니다.
SQL (82.1ms) INSERT INTO "questions" ("accepted_answer_id", "city", "created_at", "details", "province", "province_id", "question", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) [["accepted_answer_id", nil], ["city", "dd"], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["details", "greyound?"], ["province", nil], ["province_id", 2], ["question", "Whos' the biggest dog in the world"], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["user_id", 53]]
SQL (0.4ms) INSERT INTO "categorizations" ("category_id", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?) [["category_id", 2], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["question_id", 66], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00]]
레일 4 앱에서 QuestionController #create의 매개 변수를 처리한 후 서버 로그에 이 오류가 발생합니다.
Unpermitted parameters: category_ids
그리고 질문은 질문표에 삽입될 뿐입니다.
(0.2ms) BEGIN
SQL (67.6ms) INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["city", "dd"], ["created_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["province_id", 3], ["question_content", "How's your car?"], ["question_details", "is it runnign"], ["updated_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["user_id", 12]]
(31.9ms) COMMIT
질문 모델에 category_ids를 저장하지는 않지만, category_ids를 질문_컨트롤러에서 허용 매개 변수로 설정했습니다.
def question_params
params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
end
제가_ids 카테고리를 어떻게 저장해야 하는지 설명할 수 있는 사람이 있습니까?두 앱 모두 categories_controller.rb에 생성 작업이 없습니다.
두 앱 모두 동일한 세 가지 테이블입니다.
create_table "questions", force: true do |t|
t.text "question_details"
t.string "question_content"
t.integer "user_id"
t.integer "accepted_answer_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "province_id"
t.string "city"
end
create_table "categories", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "categorizations", force: true do |t|
t.integer "category_id"
t.integer "question_id"
t.datetime "created_at"
t.datetime "updated_at"
end
갱신하다
이것은 Rails 3 앱의 생성 작업입니다.
def create
@question = Question.new(params[:question])
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render json: @question, status: :created, location: @question }
else
format.html { render action: "new" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
이것은 Rails 4 앱의 생성 작업입니다.
def create
@question = Question.new(question_params)
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render json: @question, status: :created, location: @question }
else
format.html { render action: "new" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
이것은 question_params 메서드입니다.
private
def question_params
params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
end
이 https://github.com/rails/strong_parameters 은 문서의 관련 섹션인 것 같습니다.
허용되는 스칼라 유형은 String, Symbol, NilClass, 숫자, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch:Http:: 업로드된 파일 및 랙::테스트::업로드된 파일입니다.
매개 변수 값이 허용된 스칼라 값의 배열이어야 한다고 선언하려면 키를 빈 배열에 매핑합니다.
params.permit(:id => [])
내 앱에서 category_ids는 배열의 create 작업으로 전달됩니다.
"category_ids"=>["", "2"],
따라서 강력한 매개 변수를 선언할 때 category_ids를 배열로 명시적으로 설정합니다.
params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])
이제 완벽하게 작동합니다!
(중요:@Lenart가 주석에서 언급했듯이 배열 선언은 속성 목록의 끝에 있어야 합니다. 그렇지 않으면 구문 오류가 발생합니다.)
해시 배열을 허용하려는 경우an array of objectsJSON의 관점에서)
params.permit(:foo, array: [:key1, :key2])
여기서 주목해야 할 두 가지 사항:
array의마막인되합니다어야의 마지막 .permit방법.- . 합니다. 그렇지 않으면 오류가 발생합니다.
Unpermitted parameter: array이 경우 디버깅하기가 매우 어렵습니다.
다음과 같아야 합니다.
params.permit(:id => [])
또한 레일즈 버전 4+ 이후에는 다음을 사용할 수 있습니다.
params.permit(id: [])
다음과 같은 해시 구조를 가진 경우:
Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}
그리고 나서 이렇게 작동하게 되었습니다.
params.require(:link).permit(:title, time_span: [[:start, :end]])
여러 배열 필드를 허용하려면 주어진 대로 허용하면서 마지막으로 배열 필드를 나열해야 합니다.
params.require(:questions).permit(:question, :user_id, answers: [], selected_answer: [] )
(이 작업은 가능합니다.
아직 논평할 수는 없지만 Fellow Stranger 솔루션에 따라 배열 값이 되는 키가 있을 경우에도 중첩을 계속할 수 있습니다.다음과 같이:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
효과:
params.require(:model).permit(filters: [[:name, values: []]])
언급URL : https://stackoverflow.com/questions/16549382/how-to-permit-an-array-with-strong-parameters
'programing' 카테고리의 다른 글
| Xcode 10은 com.apple.commcenter.core telephony를 손상시키는 것 같습니다.xpc (0) | 2023.05.27 |
|---|---|
| 음수 정수를 0으로 설정할 .NET Math 메서드를 찾고 있습니다. (0) | 2023.05.22 |
| 스크롤 뷰어 마우스 휠이 스크롤되지 않음 (0) | 2023.05.22 |
| 인증서 확인 실패: 로컬 발급자 인증서를 가져올 수 없습니다. (0) | 2023.05.22 |
| jQuery UI 변경 이벤트 문제에 대한 날짜 선택기 (0) | 2023.05.22 |