2014-11-15 2 views
0

모두, 레일즈 4.0을 사용하고 있고 릴레이션을 사용하는데 문제가 있습니다. 나는 모델이 같은 얻을 :레일즈 동적 관계 호출

@match = SingleMatch.find(params[:id]) 

때때로 내가 (모든 질문-관계 또는 이와 유사한위한 루프) @match.question_SOME_VARIABLE.question 같은 것을 호출 할 필요가 :

class SingleMatch < ActiveRecord::Base 
belongs_to :question_1, :class_name => Question, :foreign_key => "question_1_id" 
belongs_to :question_2, :class_name => Question, :foreign_key => "question_2_id" 
belongs_to :question_3, :class_name => Question, :foreign_key => "question_3_id" 
belongs_to :question_4, :class_name => Question, :foreign_key => "question_4_id" 
belongs_to :question_5, :class_name => Question, :foreign_key => "question_5_id" 
belongs_to :question_6, :class_name => Question, :foreign_key => "question_6_id" 
belongs_to :question_7, :class_name => Question, :foreign_key => "question_7_id" 
belongs_to :question_8, :class_name => Question, :foreign_key => "question_8_id" 
belongs_to :question_9, :class_name => Question, :foreign_key => "question_9_id" 
belongs_to :question_10, :class_name => Question, :foreign_key => "question_10_id" 
belongs_to :question_11, :class_name => Question, :foreign_key => "question_11_id" 
belongs_to :question_12, :class_name => Question, :foreign_key => "question_12_id" 
belongs_to :question_13, :class_name => Question, :foreign_key => "question_13_id" 
belongs_to :question_14, :class_name => Question, :foreign_key => "question_14_id" 
belongs_to :question_15, :class_name => Question, :foreign_key => "question_15_id" 
belongs_to :question_16, :class_name => Question, :foreign_key => "question_16_id" 
belongs_to :question_17, :class_name => Question, :foreign_key => "question_17_id" 
belongs_to :question_18, :class_name => Question, :foreign_key => "question_18_id" 
belongs_to :question_19, :class_name => Question, :foreign_key => "question_19_id" 
belongs_to :question_20, :class_name => Question, :foreign_key => "question_20_id" 
belongs_to :user_1, :class_name => User, :foreign_key => "user_1_id" 
belongs_to :user_2, :class_name => User, :foreign_key => "user_2_id" 
belongs_to :winner, :class_name => User, :foreign_key => "winner_id" 

는 내가 좋아하는 내 개체를 가져옵니다. 내가 어떻게 할 수 있니?

+0

'has_many : questions'가 모든 번호가 매겨진 질문보다 의미가 없습니까? –

+0

그런 것 같지만, 지금은 앱 아키텍처를 전혀 파괴하지 않을 것입니다. – dsounded

답변

1
(1..20).each do |i| 
    @match.send("question_#{i}").question 
end 
+0

감사합니다. 완벽하게 작동합니다. 어디에서 문서를 얻을 수 있습니까? – dsounded

+0

@KyleKorver 당신은 그 문서를 가지고 있지 않습니다. 레일즈 기능이 아닌 평범한 루비입니다. 원하면 Ruby를 더 공부할 수 있습니다. –

+0

@KyleKorver 많은 사람들이 Ruby에 대한 확실한 이해없이 Rails를 배우려합니다. 레일스에 대해 진지하게 알고 있다면 루비의 기초를 배우는 데 시간을 할애하는 것이 좋습니다. – Hamed