LoginSignup
9
9

More than 5 years have passed since last update.

StrongParameters のはまりどころ

Posted at

StrongParametersActionArgs を同時に使うと、以下の様な感じのシンタックスでパラメータを制御できる。

articles_controller.rb
class ArticlesController < ApplicationController
  # ココ注目
  permits :title, :body

  def new
    @article = Article.new
  end

  def create(article)
    @article = Article.new article

    if @article.save
      redirect_to @article, notice: "New article was successfully created."
    else
      render 'new'
    end
  end
end

で、ソーシャルメディアに同時に拡散する感じのコードを書いている時にハマった。

aticles_controller.rb
class ArticlesController < ApplicationController
  # ココ注目
  permits :title, :body, :social_media
...

これだと、social_mediaに何も入らなかった。何度やっても無駄だった。謎い。
それもそのはず、viewでは↓こうなっていたから。

new.html.haml
= form_for @articles do |f|
  .field
    = f.label :social_media_facebook do
      = f.check_box :social_media, { multiple: true }, 'facebook', nil
  .field
    = f.label :social_media_twitter do
      = f.check_box :social_media, { multiple: true }, 'twitter', nil

つまり、permitsしたsocial_mediaには複数の値が入る可能性がある、っていうのをStrongParametersにあらかじめお知らせしておかなくてはいけない。
というわけで、↓こう書き換えた。

articles_controller.rb
  # ココ注目
  permits :title, :body, social_media: []
...

万事解決。

9
9
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
9
9