2012-09-04 2 views
0

지금은 이와 비슷한 모양의 게임 카드를 생성하는 코드가 있습니다.찾는 대신 ID로 레일 관계 추가?

class Pack < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :release 
    has_and_belongs_to_many :cards 

    after_create :fill_pack 

    private 

    # Randomly generate pack contents 
    def fill_pack 
    ids = self.release.cards.pluck(:id) 
    (15).times do |i| 
     self.cards << Card.find(ids[rand(ids.length)]) 
    end 
    end 
end 

나를 괴롭히는 특정 부분은 self.cards << Card.find(ids[rand(ids.length)])입니다. 그것은 15 개의 SELECT 쿼리를 만들고 있습니다! 아마 나쁜 생각 일 겁니다. ;)

이미 뽑은 ID 목록이 있습니다. 내가 그걸 사용할 수있는 방법이있을거야, 그렇지? 나는 self.cards.create :card_id => ids[rand(ids.length)]을 시도했지만 self.cards.create는 새로운 참조가 아닌 새로운 카드를 만들기위한 것입니다.

self.cards = Card.where('id in (?)', ids.sample(15)) 

또는 직접 ID를 설정합니다 : in (안된하지만 가까운)를 사용하지 왜

답변

3

self.card_ids = ids.sample(15) 
1

당신은이 작업을 수행 할 수있는 card_ids 매개 변수를 사용하여 모델을 보지 않고 그 Pack 클래스에 has_and_belongs_to_many으로 추가됩니다.

self.card_ids << ids[rand(ids.length)] 

card_ids을 설정하면 self.cards이 해당 ID에 매핑되는 모든 카드가됩니다.

+0

관계를 수정 한 후에 관계를 새로 고쳐야합니까? 그것이 비어 있다고 생각하는 것 같습니다. –

+0

ID를 실제로 추가하는 대신 ID를 설정해야하는 것처럼 보입니다. 몇 가지 빠른 테스트를 실행하면'self.card_ids = [1,2,3]'가 작동합니다. – girasquid