2011-08-04 1 views
2

내 모델입니다 :레일 모델링 - 같은 형태로 두 개의 관련 모델 (STI) 사이의 사용자 기회를주고 여기에

class BillingProfile < ActiveRecord::Base 
    belongs_to :student 
    attr_accessible :cost 
end 

class PerEventBillingProfile < BillingProfile 
    belongs_to :event_category 
end 

class FlatFeeBillingProfile < BillingProfile 
    attr_accessible :interval, :frequency 
end 

학생들은 두 가지 유형의 많은 과금 프로파일을 가질 수 있습니다. 내가 원하는 것은 학생 제작 양식의 라디오 버튼으로 PerEventBillingProfile과 FlatFeeBillingProfile을 만들 수 있습니다. 이벤트 별 라디오가 선택되면 PerEventBillingProfile 필드가 표시되고 반대의 경우도 마찬가지입니다. 이 모델 설정으로이 문제가 발생하려면 다음을 수행해야합니다.

class Student < ActiveRecord::Base 
    has_many :per_event_billing_profiles 
    has_many :flat_fee_billing_profiles 
    accepts_nested_attributes_for :per_event_billing_profiles 
    accepts_nested_attributes_for :flat_fee_billing_profiles 
end 

이렇게 생각하면 간단 할 수 있습니다. 내가 원하는 것을 얻는 더 쉬운 방법이 있습니까? 나는이 모든 것을 하나의 모델에 담아 내 컬럼에 여러 개의 NULL 값을 가질 수 있다는 것을 알았지 만, 나는 그것도 싫어한다.

답변

0

다음은이 문제를 해결 한 방법입니다. 나는 has_many : billing_profiles 줄을 Student에 보관했다.

<%= f.fields_for :billing_profiles do |builder| %> 
    <tr> 
    <%= render 'billing_profile_fields', :f => builder %> 
    <tr> 
<% end %> 

그리고 부분에 : : 양식에서 나는이 한

<td> 
    <%= f.label :type, "Profile type" %> 
    <%= f.select :type, { "Per Event" => "PerEventBillingProfile", "Flat Fee" => "FlatFeeBillingProfile" } %> 
</td> 

을 그리고 JS를 사용하여 현재 선택된 유형에 무관 필드를 숨 깁니다. 이것은 모든 유효성 검사가 BillingProfile에 있어야한다는 것을 의미합니다. 이는 Sti의 목적을 다소 상쇄합니다.