3

I'm trying to get rid of duplication of strong params in controller that handles STI models. For example I have models:

class Recipe < ActiveRecord::Base
  has many :fruits
  accepts_nested_attributes_for :fruits, allow_destroy :true
end

class Fruit < ActiveRecord::Base
  belongs_to :recipe
end

class Apple < Fruit
end

class Orange < Fruit
end

class RecipesController < Admin::BaseController
  ...
  def update
   @recipe.update_attributes recipe_params
  end
  ...
  def recipe_params
    params.require(:recipe).permit( :some_recipe_params
                                    ...
                                    ??? )
  end
end

Is there any convenient way to permit 'apple_attributes' and 'orange_attributes' without repeating them in permit options ? In future application will have more fruit types. Or maybe fruit models should be handled in another controller.

I found an ugly way to do it with whitelisted:

params.require(:recipe).permit( ... ).tap do |whitelisted|
  Recipe.fruit_types.each do |type|
    whitelisted[:"#{type.pluralize}_attributes"] = params[:recipe][:"#{type.pluralize}_attributes"] || {}
  end
end
Valery Bugakov
  • 355
  • 1
  • 10

1 Answers1

1

Permit should looks like this:

params.require(:recipe).permit fruits: [:id, :_type, ...]

Attribute "_type" must be present for all fruits otherwise you can permit only attributes from base model (Fruit)

kluka
  • 271
  • 3
  • 16
MaxKonin
  • 468
  • 3
  • 16