Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Strong Parameters - what if one of my fields is optional?

I'd not claim myself to be an expert in Rails by any stretch. One of the things that confuses me is Strong Parameters, and I've not found any really straightforward tutorials on it, with the majority of the search results dominated by hits on the rails documentation which, whilst normally accurate, I don't find in any way easy to read and can't be considered a tutorial. The github for strong params also doesn't appear to cover this.

Say I have an entity called "Resource".

class ResourcesController < ApplicationController
  ...
  def create
    @resource = Resource.new(resource_params)
    if @resource.save
      ...
      respond_with(@resource.level)
    else
      ...
    end
  end

  def update
    if @resource.update(resource_params)
      ...
      respond_with(@resource.level)
    else
      ...
    end
  end
  ...
  def resource_params
    params.require(:resource).permit(:name, :url, :description, :level_id)
  end
end

Assume I have a scaffolded form which displays the fields for name, url, description and level_id. All of the fields are mandatory. I don't know how to amend the resource_params function to ensure that name, url and level_id are mandatory when updating (or creating) a resource, but that description is optional (but should still be permitted).

I've tried removing description from the require line, and adding it on a separate line as params.permit(:description) but that has not made any difference, the field is still mandatory in the form.

Any assistance on this would be welcomed!

like image 397
Martin Greenaway Avatar asked Jan 28 '26 02:01

Martin Greenaway


1 Answers

As I said, this is nothing to do with strong parameters. You just need to remove required: true for that field to make it optional.

like image 123
Pavan Avatar answered Jan 30 '26 14:01

Pavan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!