In Rails, how do you assign all attributes of an item automatically depending on the first attribute
First part of my question is at the link above,
I have grabbed a random property using the example @ring.display_name = Ring::DISPLAY_NAME.sample. That’s not a problem. What is troubling me is grabbing the rest of the attributes.
I now need to grab @ring.gold, @ring.roll and @ring.bonus in accordance to what was randomly selected for the display_name. Here is a look at my model right now, I know it’s wrong, but can you tell me if there is a better way of doing this, one that works perhaps?
class Ring < ActiveRecord::Base
# Display_name
DISPLAY_NAME = [ 'Beginners', 'Silver', 'Gold', 'Diamond' ]
# Gold
if Ring.display_name == 'Beginners'
GOLD = [ 0 ]
end
if Ring.display_name == 'Silver'
GOLD = [ 0 ]
end
if Ring.display_name == 'Gold'
GOLD = [ 0 ]
end
if Ring.display_name == 'Diamond'
GOLD = [ 0 ]
end
# Roll
if @ring.display_name == 'Beginners'
ROLL = [ 1 ]
end
if @ring.display_name == 'Silver'
ROLL = [ 1, 2, 3 ]
end
if @ring.display_name == 'Gold'
ROLL = [ 2, 3, 4 ]
end
if @ring.display_name == 'Diamond'
ROLL = [ 4, 5, 6 ]
end
# Bonus
if Ring.display_name == 'Beginners'
BONUS = [ ring.user.level + 1 ]
end
if Ring.display_name == 'Silver'
BONUS = [ ring.user.level + (1 + rand(3)) ]
end
if Ring.display_name == 'Gold'
BONUS = [ ring.user.level + (1 + rand(5)) ]
end
if Ring.display_name == 'Diamond'
BONUS = [ ring.user.level + (1 + rand(8)) ]
end
attr_accessible :description, :display_name, :roll, :bonus, :total, :image, :gold
end
As you can see by the code, I have tried using an ‘if Ring.display_name’ and also a ‘if @ring.display_name’ Neither of these worked, as I assume whoever reading this already knows they woudn’t.
Thanks!
UPDATED!
Here is the code I am currently using. This isn’t right, I don’t quite understand how to use this technique. Take a look at what I have.
class Ring < ActiveRecord::Base
# Display_name
DISPLAY_NAME = [ 'Silver', 'Gold', 'Diamond' ]
# Rolls
ROLL = {
'Silver' => [1, 2, 3],
'Gold' => [2, 3, 4],
'Diamond' => [4, 5, 6]
}
self.roll = ROLL[self.display_name]
BUY = {
'Silver' => [100..180],
'Gold' => [140..200],
'Diamond' => [180..350]
}
self.buy = BUY[self.display_name]
BONUS = {
'Silver' => [(1 + rand(3))],
'Gold' => [(3 + rand(5))],
'Diamond' => [(5 + rand(8))]
}
self.bonus = BONUS[self.display_name].call
attr_accessible :user, :active, :display_name, :description, :gold, :buy, :sell, :roll, :bonus, :total, :image, :description
end
and in my controller:
def create
@ring = Ring.new
@ring.display_name = Ring::DISPLAY_NAME.sample
@ring.save
redirect_to @ring
end
The way I understand it, if I tell it to pick a random display_name, all other fields will be filled in according to what I have in the model, is that correct?
You can make hashes out of your conditionals, like following: