Last active
July 12, 2023 00:15
-
-
Save Slike9/d8b7280c4cb48f11568b to your computer and use it in GitHub Desktop.
rails ModelForm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ModelForm | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :model_class | |
self.model_class = self.superclass | |
end | |
module ClassMethods | |
def model_name | |
model_class.model_name | |
end | |
def permit(*permitted_attrs) | |
@permitted_attrs = permitted_attrs | |
end | |
def permitted_attrs | |
@permitted_attrs | |
end | |
def wrap(model) | |
model.becomes(self).tap do |form| | |
form.model = model | |
end | |
end | |
end | |
def assign_attributes(attrs = {}) | |
if attrs.respond_to?(:permitted?) | |
attrs = attrs.permit(*self.class.permitted_attrs) | |
end | |
super(attrs) | |
end | |
def model | |
@model ||= self.becomes(self.class.model_class) | |
end | |
def model=(value) | |
@model = value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
app/models/post.rb
app/forms/post_form.rb
app/controllers/posts_controller.rb