【发布时间】:2015-03-01 10:51:17
【问题描述】:
我正在尝试消除处理 STI 模型的控制器中强参数的重复。例如我有模型:
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
是否有任何方便的方法来允许“apple_attributes”和“orange_attributes”而不在允许选项中重复它们?在未来的应用中将有更多的水果类型。或者水果模型应该在另一个控制器中处理。
我发现了一种使用白名单的丑陋方法:
params.require(:recipe).permit( ... ).tap do |whitelisted|
Recipe.fruit_types.each do |type|
whitelisted[:"#{type.pluralize}_attributes"] = params[:recipe][:"#{type.pluralize}_attributes"] || {}
end
end
【问题讨论】:
标签: ruby-on-rails strong-parameters single-table-inheritance