Display all versions of individual records in Papertrail

后端 未结 2 1604
花落未央
花落未央 2021-01-16 00:39

I\'m building a league system and currently it stores and updates the players \'elo score\' depending on the result. Now, I\'m trying to add in \'HighCharts\' to display the

相关标签:
2条回答
  • 2021-01-16 01:35

    Here's a one-liner version of @MrDanA's answer :

    elo_scores = self.versions.map{|version| version.reify.elo_scores}
    

    note that you can't check if version.reify.nil? though

    0 讨论(0)
  • 2021-01-16 01:41

    What you did here:

    @player.versions.map { |version| version.reify.elo_score }
    

    Is perfectly fine to take all those scores and put them in an array. The problem that you're getting (the nil:NilClass stuff) is coming because at least one reify is nil. That is, that some version doesn't have a reify.

    If each version is supposed to have a reify, be sure to add that as a model validation, and find in your code where the reify is being set and see why it's nil.

    If it's okay for a version to have a nil reify, you could accomplish it a number of ways, but the straightforward and explicit way would look like this:

    elo_scores = []
    @player.versions.each do |version|
        unless version.reify.nil?
            elo_scores << version.reify.elo_score
        end
    end
    

    I would suggest putting this in to a method, like get_elo_scores, and then you could more easily call it like:

    @player.get_elo_scores
    

    EDIT For clarification from the comments:

    Your User model (or Player model, whatever you named it) should have a method that looks like this:

    def get_elo_scores
        elo_scores = []
        self.versions.each do |version|
            unless version.reify.nil?
                elo_scores << version.reify.elo_score
            end
        end
        return elo_scores
    end
    

    I apologize for not making this clearer, but you won't have access to @player within this method because that only exists in the context of your controller and view. The above is now a proper instance method: it will call .versions upon itself, and the rest is fine. I also added an explicit return call at the end.

    Now you will be able to call @player.get_elo_scores on any User (or Player) object.

    Hope that helps!

    0 讨论(0)
提交回复
热议问题