保持参数干轨干燥

时间:2019-09-20 06:36:25

标签: ruby-on-rails ruby dry

我有一个名为“ seo”的模型

class Seo < ApplicationRecord
    belongs_to :seoable, polymorphic: true
    # more code
  end

我的应用程序中有很多模型has_one seo。例如

 class Post < ApplicationRecord
    has_one :seo, as: :seoable
    accepts_nested_attributes_for :seo, dependent: :destroy
    # more code
  end

我的问题是,使控制器中的参数保持干燥的最佳方法是什么?例如,我的posts_controller中有以下代码

def post_params
  params.require(:post).permit(seo_attributes: [:id, :title, :meta_description, :etc])
end

每个模型都会重复上述操作。我该如何保持干态?

4 个答案:

答案 0 :(得分:2)

我认为这是一个可以使用concern的示例:

# in app/models/concern/seoable.rb
require 'active_support/concern'

module Seoable
  extend ActiveSupport::Concern
  included do
    has_one :seo, as: :seoable
    accepts_nested_attributes_for :seo, dependent: :destroy
  end
end

# in your models
class Post < ApplicationRecord
  include Seoable
end

对于控制器,您可以在AplicationController中添加一个方法来简化调用:

# in the application_controller
def params_with_seo_attributes(namespace)
  params.require(namespace).permit(seo_attributes: [:id, :title, :meta_description, :etc])
end

# and use it in your controllers like this
def post_params
  params_with_seo_attributes(:post)
end

答案 1 :(得分:0)

您可以使一个具有该post_params方法的控制器,然后需要使用该方法的其余控制器可以从该控制器继承

答案 2 :(得分:0)

因此,如果在多个模型中重复使用has_one :seo, as: :seoableaccepts_nested_attributes_for :seo, dependent: :destroy,则可以对其使用 Rails Concerns

如果您想学习如何提出疑虑,请参见this question

答案 3 :(得分:0)

您可以拥有如下基本控制器

class ResourceController < ApplicationController
        private
        def resource_params
            params.require(resource_name).permit(seo_attributes: [:id, :title, :meta_description, :etc])
        end
end

在后期控制器中,您可以像这样干用它们

class PostController < ResourceController    
            def resource_name
                :post
            end
end

然后再次在Blog之类的其他任何控制器中使用,如下所示

class BlogController < ResourceController    
                def resource_name
                    :blog
                end
    end