Last active
June 1, 2017 10:18
-
-
Save palkan/ad0b0ac7aba4501e513fc1b35a764f10 to your computer and use it in GitHub Desktop.
STI update
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 StiUpdate | |
def as(type) | |
if self.type == type | |
self | |
else | |
klass = type.camelize.constantize | |
if klass.nil? | |
self | |
else | |
became = self.becomes!(klass) | |
# the only hack here: @errors instance may contain a reference to the source object | |
became.instance_variable_set(:@errors, nil) | |
became | |
end | |
end | |
end | |
def update_as(type, params) | |
became = as(type) | |
became.update(params) | |
became | |
end | |
end | |
# Usage example (e.g. in your controller) | |
def update | |
@post = @post.update_as(post_params[:type] || @post.type, post_params) | |
if @post.valid? | |
... | |
else | |
... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment