I have a Character
model that has a CharClass
and ClassPerks
child.
Currently I am duplicating my logic a lot by manually assigning data.
My Character
index and create:
def index
@campaign = Campaign.find_by_id(params[:campaign_id])
@characters = @campaign.characters
render json: {
characters: @characters
}
end
def create
@campaign = Campaign.find_by_id(params[:campaign_id])
@charClass = CharClass.find_by_id(params[:character_char_class_id])
@character = @campaign.characters.new(character_params)
@character.char_class_id = params[:character_char_class_id]
if @character.save!
render status: 201, json: {
message: "Successfull added this character to the campaign!",
character_name: @character.character_name + ' the ' + @charClass.class_name,
character_class: @charClass.class_name,
character_level: @character.character_level,
character_experience: @character.character_experience,
character_gold: @character.character_gold,
character_perks: get_names(@character.character_perks),
character_image: @character.character_image
}
else
render status: 404, json: {
message: "Something went wrong: Check line 24 of the Character Controller"
}
end
end
I am manually assigning character_class
and character_image
despite both of these ALWAYS being the same based on their character_class
.
Inside of the character.rb
I am doing this to assign them post-create:
after_create :add_perks, :save_class
def add_perks
self.class_perks.each do |perk|
self.character_perks.create(class_perk_id: perk.id)
end
end
def save_class()
case self.char_class_id
when 1 # Mindthief
self.character_image = "https://gloomhavenil.files.wordpress.com/2017/12/11849117_616974988445216_217288420_n.jpg?w=480"
self.character_class = "Mindthief"
self.save
when 2 # Tinkerer
self.character_image = "http://www.cephalofair.com/wp-content/uploads/2015/04/Quatryl-Tinkerer.jpg"
self.character_class = "Tinkerer"
self.save
# when 'Sawbones'
# else
end
end
end
It is working, but I am unsure how to do this better/appropriately. I removed useless fields but you'll see below I have the relations set up appropriately.
create_table "char_classes", force: :cascade do |t|
t.string "class_name"
t.string "class_image"
t.string "class_perks"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "characters", force: :cascade do |t|
t.string "character_class"
t.string "character_image"
t.integer "char_class_id"
t.index ["campaign_id"], name: "index_characters_on_campaign_id"
t.index ["char_class_id"], name: "index_characters_on_char_class_id"
end
I can do Character.first.char_class.class_name
and I will get the appropriate result; so I am back to assuming this method I'm following is very incorrect.