LightBox
LightBox

Reputation: 3425

rails undefined method when iterating of array of methods

I'm a rails beginner and trying to put some code in the model. The code below is an illustration.

View:

Player_stats: <%= @player.player_pass_completion_ratio %>

Model:

class Player < ActiveRecord::Base
 has_many :lefthandstats
 has_many :righthandstats

def player_pass_completion_ratio
 Hands = [ lefthandstats, righthandstats] #These are objects & calling   @player.lefthandstats.find_with_passes directly generally works

 if self.category ==  "Hands"
  total_usual_passes = 500
  Hands.each do |cmethod|
    if self.cmethod.find_with_passes(:passes, :first, {:conditions => 'passes>200' })   then accuratestats += 1 end
  end
 end

accuracy = (accuratestats/total_usual_passes)*100
end

I get an undefined method "cmethod" when I try to call the code from the view. Any advice is greatly appreciated.

Upvotes: 0

Views: 67

Answers (4)

sjain
sjain

Reputation: 23344

First correct your code by replacing // by # as in rails we use # to comment the code as mentioned by akofink.

Then consider this in context of your code:

@result = Player.all

@result.each do |player|

player.name

end

Here @result is returning a collection of players. So you can use a loop with @result.each such that for each result as player, you are getting a name of each player.

Correct your code with the knowledge of what is in the above.

Upvotes: 0

sevenseacat
sevenseacat

Reputation: 25029

Your code is calling self.cmethod, which will try to call the cmethod method on your object (which doesn't exist).

I believe what you're trying to do is something like the following:

hands = [:lefthandstats, :righthandstats]
hands.each do |cmethod|
  self.send(cmethod).... #rest of your code goes here
end

This will dynamically call the lefthandstats and righthandstats methods on your object.

Upvotes: 1

akofink
akofink

Reputation: 689

Comments in ruby use the # character, not //

Upvotes: 2

GSP
GSP

Reputation: 3789

Get rid of "self.cmethod" and just use "cmethod"

if cmethod.find_with_passes....

In the scope of the block "cmethod" is just a local variable. By putting self in front of it, ruby assumed you were calling a method on the containing class instance.

Upvotes: 1

Related Questions