I have a model named “seo”
class Seo < ApplicationRecord
belongs_to :seoable, polymorphic: true
# more code
end
Many models in my application has_one seo. For example
class Post < ApplicationRecord
has_one :seo, as: :seoable
accepts_nested_attributes_for :seo, dependent: :destroy
# more code
end
My question is, what is the best way to keep params in my controllers dry. For example I have the following code in my posts_controller
def post_params
params.require(:post).permit(seo_attributes: [:id, :title, :meta_description, :etc])
end
Every model will repeat the above. How do I keep this DRY?
4
Answers
You could make one controller that has that
post_params
method, and then the rest of the controllers that need to use it, can inherit from that controllerSo if the
has_one :seo, as: :seoable
andaccepts_nested_attributes_for :seo, dependent: :destroy
are repeated in multiple models then you can use Rails Concerns for it.If you want to learn how to make concerns see this question
You can have a base controller like the follows
And in post controller you can use them as dry like this
And again use in any other controller like Blog as follows
I think this is an example where you could use a concern:
And for the controllers, you could add a method into
AplicationController
that allows simplified the call: