Last active
August 9, 2021 12:33
-
-
Save danielpuglisi/3c679531672a76cb9a91 to your computer and use it in GitHub Desktop.
Rails examples: Single Table Inheritance (STI), strong parameters, single controller.
This file contains 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
# Variant 1 | |
def user_params(type) | |
params.require(type.to_sym).permit(attributes) | |
end | |
# Variant 2 | |
def user_params(type) | |
case type | |
when "user" | |
params.require(:user).permit(user_attributes) | |
when "apprentice" | |
params.require(:apprentice).permit(apprentice_attributes) | |
end | |
end | |
# Variant 3 | |
def update | |
... | |
if @user.update(send("#{@user.type.underscore.to_sym}_params")) | |
... | |
end | |
def user_params | |
params.require(:user).permit(attributes) | |
end | |
def apprentice_params | |
params.require(:apprentice).permit(attributes) | |
end | |
# Variant 4 | |
https://github.com/T-Dnzt/sti-with-rails4/blob/master/app/controllers/animals_controller.rb |
Thanks! To get the name of the model used in the parameters, you can also use:
@model_instance.model_name.param_key
And what about that?
def user_params
type = @user.type.underscore.to_sym
params.require(type).permit(:name, :age)
end
Thanks! To get the name of the model used in the parameters, you can also use:
@model_instance.model_name.param_key
👍 - cleanest IMO. Thanks @flavio-b!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just stumbled upon this and found a handy solution for my problem, thank you :)