Using compact_blank to Filter Form Parameters in Rails

In Rails 6.1, a new method called compact_blank was introduced to help filter out nil and blank elements from an array. This method can be particularly useful when working with form parameters, where some fields may be left blank or undefined.

To use compact_blank, call it on the array or hash that you want to filter. Here’s an example of how to use compact_blank with form parameters in a Rails controller:

1
2
3
4
5
6
7
8
9
10
11
def update
  @user = User.find(params[:id])
  @user.update(user_params)
  redirect_to @user
end

private

def user_params
  params.require(:user).permit(:name, :email, :phone).compact_blank
end

In this example, the user_params method returns a hash of permitted parameters, which may include nil or blank values. The compact_blank method is then called on the user_params hash, which returns a new hash with the nil and blank values removed. This filtered hash is then passed to the update method on the @user object, which updates the corresponding attributes.

By using compact_blank, you can simplify your code and avoid having to manually filter out nil and blank elements.