2013-02-09 8 views
0

가정하자 나는이 다음 모델 :방지 저장 중복 된 문자열

class Event < ActiveRecord::Base 
     has_many :tips 
    end 

    class Tip < ActiveRecord::Base 
    end 

이 팁 설명은 MySQL 데이터베이스에 불과 VARCHAR(140), 대부분 값을 통조림, 예 : "비옷을 착용"등 또는 "수표 소지". 그러나 동일한 값을 가진 많은 수의 문자열을 저장하는 것을 피하기 위해 정규화를 사용하고 싶습니다. Tip 모델에 belongs_to :event을 추가하면 event_id 값은 많은 중복 팁으로 이어질 것입니다.

tip_id <---> tip_description 매핑을 수동으로 관리하지 않고도 정규화의 이점을 얻을 수있는 방법은 무엇입니까?

+0

는 어떻게'belongs_to' 리드 중복? 간단히 말해 줄 수 있니? – codeit

+0

두 이벤트 A와 B의 설명이 각각 "우산 가져 오기"인 팁이있는 경우, A.id! = B.id이므로 두 번째 항목이'tips' 테이블에 있습니다. – tlehman

답변

2

당신이 다음 events_tips을 만들 has_and_belongs_to_many

class Event < ActiveRecord::Base 
    has_and_belongs_to_many :tips 
end 

class Tip < ActiveRecord::Base 
    has_and_belongs_to_many :events 
end 

마이그레이션을 사용하여 테이블에 반복되는 항목을 피하려면 : 컨트롤러에서

class CreateEventsTips < ActiveRecord::Migration 
    def change 
    create_table :events_tips, :id => false do |t| 
     t.integer :event_id 
     t.integer :tip_id 
    end 
    end 
end 

:

tip = Tip.find_or_create_by_tip_description(params[:tip][:description]) 
Event.find_by_id(params[:id]).tips << tip 
+0

아, 그건 완벽하게 이해합니다. 고마워요! – tlehman