Sa S. wrote in post #1074690:
> Thanks for the help! Although I'm not sure I totally understand it,
> still a bit of a noob. So if I wanted to do something as simple as
> subtract the user's handicap from the course's handicap, how would I
> create a method for that in the Player model? (sorry maybe you might
> have done it already but I'm not sure what .gt and .lt mean)
>
> Basically something like
>
> class Player
>
> def handicaps_difference
>    Course.handicap - handicap (from the player)
> end

Given that with a many-to-many relationship (has_and_belongs_to_many) a 
single player will be associated to many courses and one course will be 
associated to many players. So in order to do that sort of math you'll 
need to iterate through them.

Player will have a method, added by ActiveRecord named "courses"...

a_player.courses

I assume here that you want to first select a player:

a_player = Player.find(:id)

Then I assume you want to list all the courses associated with this one 
player with the handicap difference:

a_player.courses.each do |course|
  puts course.handicap_difference(a_player)
end

Where each course can calculate the handicap difference with a given 
player:

class Course
  def handicap_different(player)
    player.handicap - self.handicap
  end
end

But even better would be to expose the join table with its own object 
using has_many :through. Then you can put the calculation in the object 
that "knows" about both sides:

class CourseAssignment  # The exposed join table
  has_one :player
  has_one :course

  def handicap_difference
    player.handicap - course.handicap
  end
end

Again the "player" and "course" methods will be added by ActiveRecord to 
the CourseAssignment object.

http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to