How does “only:” at “before_action” work in Rails?

The only option of before_action defines one action OR a list of actions when the method/block will be executed first.

Ex:

# defined actions: [:show, :edit, :update, :destroy]
before_action :set_newsletter_email, only: [:show, :edit]

The set_newsletter_email method will be called just before the show and edit actions.


The opposite option except define when NOT to execute the method/block.

# defined actions: [:show, :edit, :update, :destroy]
before_action :set_newsletter_email, except: [:show, :edit]

The set_newsletter_email method will be called for all existing actions EXCEPT show and edit.


only / except is just a kind of whitelist/blacklist.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)