Skip to content

Instantly share code, notes, and snippets.

@palkan
Last active June 1, 2017 10:18
Show Gist options
  • Save palkan/ad0b0ac7aba4501e513fc1b35a764f10 to your computer and use it in GitHub Desktop.
Save palkan/ad0b0ac7aba4501e513fc1b35a764f10 to your computer and use it in GitHub Desktop.
STI update
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