All posts

Rails params cheatsheet

A few notes to refer to when not sure about how to handle rails parameters:

*This is not a comprehensive post. It is a brief reference for developers with some experience using Rails but haven’t used it recently.

  1. Use the require method on the params object when detecting the presence of a specific model, like author below:
private

def author_params
  params.require(:author).permit(:name, :organization_id, :post_id)
end
  1. Use the permit method, referenced above, when you want to save the params to the database using an ActiveRecord model.

  2. You don’t need to use the require method before calling permit. The require method does not change the object.

  3. If you only need to reference one parameter key, you can just use the key/value accessor [] directly in the controller method:

org = Organization.find_by!(external_id: params[:external_id])
  1. If you have a params object with complex data structures such as nested collections like the below example:
{"author" => {"post_title" => "first post", "tags" => [{"id" => 1, "name" => "Food"}]}

You can permit those parameters using the code the below. Just make sure the collections are the last to be permitted in the method, in this example tags:

params.permit(author: [:post_title, tags: [:id, :name]])

More Ruby cheatsheets: Ruby HTTP gem, Rails error handling Rails DB encryption


Resources I found useful when building this: