2017-08-19 77 views
0

我是RoR開發的新手,對於參數如何從HTML視圖傳遞到控制器有點困惑。我已經看到它使用這樣的私有方法的在線的幾個例子:使用RoR將參數從窗體傳遞到控制器

private 
def message_params 
    params.require(:message).permit(:content) 
end 

我一直在尋找一些澄清網上爲這是什麼方法呢,它是如何工作的,但我只遇到這用木樁/篇該方法而不是解釋它做了什麼。

我希望有人能解釋如何通過POST請求通過表單傳遞的值(/ filters?),require和permit關鍵字的含義以及如何更改此方法以適合我自己的使用。

例如,如果我需要得到一個新的書,我會做這樣的數據:

private 
    def book_params 
     params.require(:book_name).require(:ISBN).require(:Author).permit(:Illustrator) 
    end 

以上將是有效的因爲我的書對象具有這些領域?

任何澄清,將不勝感激。

謝謝。

+1

武名看[強參數(HTTP:// edgeguides .rubyonrails.org/action_controller_overview.html#強參數)。 – Gerry

回答

0

這裏是一些信息(我使用你的示例模型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 
+0

謝謝偉大的答案。假設.require()方法將對象作爲參數,並且.permit方法將這些字段作爲參數,我是否正確的一個問題是? –

+0

是的,正如你從我的答案中看到的那樣,對象是書本和領域都在裏面 – widjajayd

0

這種函數用於白名單params - 即說你有一個消息模型,並通過控制器的行動,你應該只能夠改變內容。也許還有一個作者字段 - 但即使有人通過表單傳遞它,你也不想更新它。

params.require(:message) 

會回到你PARAMS [:消息]。許可證意味着您只允許通過內容字段。

參見:http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

我需要看到你的模型設置,但我會假設給你想要的東西更像是一本書的模型:

params.require(:book).permit(:illustrator, :author, :isbn) 
相關問題