1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

raisのパラメーターについて

Posted at

paramsについて

コントローラー内でリクエストから送信されたパラメータを扱うためのメソッドです。これを使うことで、フォームから送信されたデータやURLのクエリパラメータを簡単に取得できます。

基本的な使い方

  1. フォームデータの取得:
    フォームから送信されたデータはparamsを使って取得できます。例えば、以下のようなフォームがあります。
<form action="/questions" method="post">
  <input type="text" name="question[title]" />
  <input type="text" name="question[content]" />
  <input type="submit" />
</form>

このフォームが送信されると、コントローラーでは以下のようにデータを取得できます。

defcreate
  @question = Question.new(params[:question])
if @question.save
    redirect_to action: :index
else
    render :new
endend

2.ストロングパラメーター:
セキュリティを確保するために、特定のパラメータだけを許可する「ストロングパラメータ」を使用します。以下のように設定します。

defcreate
  @question = Question.new(question_params)
if @question.save
    redirect_to action: :index
else
    render :new
endend

private

defquestion_params
  params.require(:question).permit(:title, :content, :name)
end

具体的なシナリオと使用例

  1. 新規作成フォームの送信データを扱う:
    フォームでユーザーが入力したデータを、paramsを使って取得し、新しいモデルオブジェクトを作成するのが一般的です。
  2. URLのクエリパラメータを取得する:
    URLに含まれるクエリパラメータ(例: ?search=example)を取得することもできます。
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?