简体   繁体   中英

Ruby: Calling an instance method from another class

I have two models: Draft and Pick.

Draft has an instance method @available_players that has an array of players available in the draft. When I call @available_players from inside a method in Draft.rb, I get the array of players as expected.

Pick is a model that records the player_id, draft_id and team_id. I am also trying to get it to remove players from the player array inside Draft. When I try to access the player array inside Draft.rb (using (draft_instance).available_players) I get nil.

Draft.rb:

def set_available_players
    Player.all.each do |player|
        @available_players << player
    end
end    

def available_players
    @available_players
end

Pick.rb

def set_draft_object
    @draft_object = Draft.find(self.draft_id)
end

def available_players
    @draft_object.available_players
end

The method available_players inside PICK produces nil. What's strange is that if I call @draft_object.id I will get the correct id! It just won't return the non active record value such as 'draft_object.available_players'.

@available_players works from inside the draft model and when I test it in the draft_spec.rb but not in the pick_spec.rb.

I've read through some of the instance vs. class method documentation but I have many instances of Draft so I believe I want to have it be an instance method.

first of all use attr_reader instead of function: good explanation

if you are trying to do Pick.draft_object use @@ or def self.draft_object

but the best way is to use ActiveModel as it should

Where do you call your set_available_players method? It looks like it's not being called at all - and if so, that explains why available_players returns null.

This should work:

Pick.rb

def set_draft_object
    @draft_object = Draft.find(self.draft_id)
    @draft_object.set_available_players # THIS BIT IS NEEDED
end

def available_players
    @draft_object.available_players
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM