[英]Passing parameters from form to controller using RoR
我是RoR開發的新手,並對如何將參數從HTML視圖傳遞到控制器感到困惑。 我在網上看到了一些使用私有方法的示例,例如:
private
def message_params
params.require(:message).permit(:content)
end
我一直在網上尋找有關此方法的作用及其工作方式的說明,但是我只遇到使用該方法的帖子/文章,而沒有解釋它的作用。
我希望有人能解釋該方法如何通過POST請求獲取通過表單傳遞的(/ filters?)值,require和allow關鍵字的含義以及如何更改此方法以適合自己的用法。
例如,如果我需要獲取有關新書的數據,我會這樣做:
private
def book_params
params.require(:book_name).require(:ISBN).require(:Author).permit(:Illustrator)
end
鑒於我的書對象具有這些字段,以上內容是否有效?
任何澄清將不勝感激。
謝謝。
這種功能用於將參數列入白名單-即說您有一個消息模型,並且通過控制器操作,您只能更改內容。 也許還有一個author字段-但是即使有人將其通過表單傳遞,您也不想更新它。
params.require(:message)
將返回給您params [:message]。 允許表示您只允許內容字段通過。
請參閱: http : //edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters
我需要查看您的模型設置,但是假設給定了書本模型,您將需要更類似於以下內容的東西:
params.require(:book).permit(:illustrator, :author, :isbn)
這是一些信息(我正在使用示例模型Book和BookController),可能可以幫助您更多地了解
提交表單時,rails自動調用create方法,在create方法內部,您將看到Book.new(book_params),book_params將調用private方法並檢查允許的字段,如果還有其他字段已提交但未在您的允許框內列出那么它將不會傳遞到保存命令
class BooksController < ApplicationController
def create
@book = Book.new(book_params)
if @book.save
flash[:success] = 'Data save successfully'
redirect_to books_path
else
render :new
end
end
private
def book_params
params.require(:book).permit(
:book_name,
:isbn,
:author,
:illustrator)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.