开发者

Rails - Assigning values to data entered by users in a model's form?

开发者 https://www.devze.com 2023-04-05 01:14 出处:网络
I have a model, Statistic, that has 6 statistics for a Character model. Users can enter values for Strength, Intelligence and so on. What I want to do is automatically assign a value for a bonus or a

I have a model, Statistic, that has 6 statistics for a Character model. Users can enter values for Strength, Intelligence and so on. What I want to do is automatically assign a value for a bonus or a penalty based on the value entered by the user. For example, if a 10 or 11 is entered, the bonus will be 0. If a 14 or 15 is entered, it will be 2. Any tips on how to write this method? Thanks!


This has been a big help, but I've hit another snag. I've defined this in the Show method in Characters controller as such:

@con_modifier = @character.statistic.con_modifier

So I can call it from my Character view (where most of this information is displayed) I've got a Fortitude model for Fortitude saves, and I'd like to use the con_modifier in the logic to calculate a total. How do I call a foreign model correctly this way? I have:

def total
  fortitude_base.to_i + ability.to_i + magic.to_i + misc.to_i
end

And I tried cha开发者_Go百科nging it to:

def total
  fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i
end

But then I get this error:

nil can't be coerced into Fixnum

So obviously it isn't calling up the correct information. Any ideas? Do I need to define it in my Fortitudes controller as well, or can I simply define it in the Fortitude model and call it in the view that way?


Smells like D&D. Consulting my old Player's Handbook indicates that the modifier for an attribute value of n is simply (n - 10) / 2.

So you'd just the attribute value through that simple formula and you'd have your modifier. I'd probably have a class method in the Attribute class:

class Attribute
    #...
    def self.modifier_for(attribute_score)
        (attribute_score.to_i - 10) / 2
    end
end

And then hook that up to your Player with something like this:

class Player
    #...
    def wis_modifier
        Attribute.modifier_for(wis)
    end
    def modifier(attr)
        self.send(attr.to_s + '_modifier')
    end
end

will_save += p.modifier(:wis)

You could probably get fancier if you wanted but simple is a good start and you can always get your local cleric to heal your code (or use your +3 Flaming Ax of Code Refactoring) later if necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号