2011-01-23 3 views
0

저는 사용자 모델과 목표 모델을 가지고 있습니다. 목표 모델에는 이름과 유형 열이 있으며 여기에는 다음 세 개의 레코드가 있습니다.레일에 사용자 정의 메타 데이터가있는 2 개의 테이블을 결합하십시오.

name   | type 
------------------------ 
Read Novels | Reading 
Read Newspaper | Reading 
Write Reviews | Writing 

지금 나는 그들이 그것을 (days_per_month를) 할 각 사용자가 매월 (hours_per_month)이 활동에 지출 시간 수를 입력 할 수있는 인터페이스 및 다른 일 수를 제공합니다.

이상적으로는, 나는 정적 목표 속성에 내가 사용에 목표를 조인이 새 테이블/모델을 생성하는 방법을

current_user = User.find(params[:id]) 

current_user.goals.each do |goal| 
    puts goal.name 
    puts goal.type 
    puts goal.hours_per_month 
    puts goal.days_per_month 
end 

같은 데이터로 작업하고 액세스 할 수 있도록하려면, 그리고 것 위의 코드 샘플과 같이 사용자가 값을 채웠습니까?

답변

1

당신은 Activity 모델을 만들고 그것을 같은 테이블 정의 줄 수 :

활동 :

  • USER_ID
  • goal_id
  • hours_per_month
  • days_per_month

을 그런 다음 추가 :

User 
    has_many :activities 
    has_many :goals, :through => :activity 

Goal 
    has_many :activities 
    has_many :users, :through => :activity 

Activity 
    belongs_to :user 
    belongs_to :goal 

대부분의 작업 iirc를 수행 할 수 있습니다.

1

표 goals_users

column: user_id 
column: goal_id 
column: hours_worked 

모델 :

사용자 :

has_and_belongs_to_many :goals 

목표 :

has_and_belongs_to_many :users 

def hours_per_month 
    #calculate 
end 

def hours_per_day 
    #calculate 
end 

분명히 원하는대로 추가 열을 설정할 수 있습니다. AR을 사용하여 모든 모델에서 추가

은 직접 중간 기록에 액세스해야합니다 합류했다.

관련 문제