I'm looking for advice / best practice to avoid doing a deeply nested set of IF
/THEN
statements in Rails. The intention is to seed a database.
Short version - without specific examples
My basic pattern is 1 .. n
IF(1st_object_exists) THEN
2nd_object = 1st_object.relationship.create!(args)
IF (2nd_object) THEN
3rd_object ... so on & so forth down 9 levels ...
END
END
Where the issue exists is I have two additional, unrelated relationships which should populate at each step back at each step & potentially 4 or 5 that need to populate.
Long version - with specific examples
Basic setup: each game is a campaign. Each campaign will have players, each player will have a country (each country also has a join table back to the campaign), each country a state...
I'm hoping there's an elegant way of doing this instead without using too many object chains (".")'s, but perfectly happy to do so if that's the only way.
Originally, I was doing Campaign.Players.Countries.create!(args)
, which errors with not valid method for Countries or Players until I eliminate one or the other. Eliminating this leaves me seeding the relationship value for the other has_many else where though...
I also had tried using the same join tables with models using has_many, through: for this pattern ...
user = User.first
if(user) then
campaign = user.campaigns.create!(args)
if(campaign) then
new_player = game_instance.players.create!(args)
if(new_player) then
new_country = new_player.countries.create!(args)
if(new_country) then
new_country.states.create!(args)
end
end
end
end
My models are a bit of a mess but all present ...
There are several primary tables & a join table between each (including a belongs_to matching the has_many's pointed at it from other files)
user.rb
has_many :userplays
has_many :players, through: :userplays
has_many :usercamps
has_many :campaigns, through: :usercamps
campaign.rb
belongs_to :users
has_many :campplays
has_many :players, through: :campplays
has_many :campcounts
has_many :countries, through: :campcounts
player.rb
has_many :countries
has_many :campplays
has_many :campaigns, through: :campplays
has_one :userplay
has_one :user, through: :userplay
country.rb
has_many :states
has_many :counties, through: :state
belongs_to :player
belongs_to :campcount
As stated above, all join tables follow this format, but after the first 4 or 5 letters I truncate the table name for ease of length...
<1stTableName><2ndTableName>.rb
belongs_to :1stTableName
belongs_to :2ndTableName