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 quick reference if you have some experience with Rails but haven’t used it recently.

  1. You most often use the require method when detecting the presence of a specific model, like author below:

def author_params
  params.require(:author).permit(:name, :organization_id, :post_id)
  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])
  4. If you have a params object in a similar format to the below, with nested collections:
    {"author" => {"post_title" => "first post", "tags" => [{"id" => 1, "name" => "Food"}]}

You can permit those parameters like the below. Just make sure the collections are the last to be permitted in the method:

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

Resources I found useful when building this: