How to add custom attributes in Spree

Reading Time: < 1 minute

Having had the chance to work with Spree 2.2, the latest version at the moment, I noticed that sometimes you need to extend some permitted_attributes inside controllers. More specifically, sometimes you need to add attributes to your DB.

Having said this, I thought I'd like to find out if there's more than a single way to achieve this. I know of one particular method, which I'm going to show you here:

  • Single attribute

    before_action :permit_new_attribute
    private
    def permit_new_attribute
      permitted_source_attributes << :new_attribute
    end
    
  • Multiple attributes

    def object_params
      params.require(:object).permit(permitted_object_attributes, new_attributes)
    end
    def new_attributes
      permitted_object_attributes << [:new_attribute_1, :new_attribute_2]
    end
    
  • Unstructured (at the beggining of the controller)

    Spree::PermittedAttributes.object_attributes << [:new_attribute_1, :new_attribute_2]
    

So, what do you think, do you know of any other ways to do this, please please share with us on the comments section, I'd love to hear from you!

Thanks for reading.

0 Shares:
You May Also Like