I am trying to build a soccer game to experiment with ruby. The associations are below:
Match.rb
class Match < ActiveRecord::Base
belongs_to :home_user, :class_name => 'User', :foreign_key => 'home_user_id'
belongs_to :away_user, :class_name => 'User', :foreign_key => 'away_user_id'
User.rb
class User < ActiveRecord::Base
has_many :home_matches, :class_name => 'Match', :foreign_key => 'home_user_id'
has_many :away_matches, :class_name => 'Match', :foreign_key => 'away_user_id'
My question is how I can assign the home_user and away_user for a match? I thought of an initializing method like:
def initialize(home_user, away_user)
@home_user = User.find(1)
@away_user = User.find(2)
end
but how to put the code to find the user deciding to match and the user offered to match? I suppose I should define them at the moment the user clicks the “set_match” link and send these user_ids to the method but how? The problem is that ruby is the first OOL I’m learning. I already learned the classes and objects and encapsulation and variables etc.. but need further guidance about methods. Thank you in advance.
I wouldn’t use the initialize method, as when your model subclasses ActiveRecord::Base, it has a good initialize method for setting all the attributes.
However, you can do something like this.
Then in your controller
I basically set it up so the update action on the match controller will accept one option to update the user relationships, or just accept the usual hash of update parameters.