2013-02-09 101 views
0

假設我有以下型號:避免存儲重複的字符串

class Event < ActiveRecord::Base 
     has_many :tips 
    end 

    class Tip < ActiveRecord::Base 
    end 

小費描述僅僅是在MySQL數據庫中的VARCHAR(140),其中大部分都是罐頭值,如「穿雨衣」或「攜帶支票簿」。我想使用規範化來避免存儲大量具有相同值的字符串,但是,如果將belongs_to :event添加到Tip模型中,event_id值將導致許多重複的提示。

如何在不手動管理tip_id <---> tip_description映射的情況下獲得規範化的好處?

+0

如何將'belongs_to'鉛複製?你能簡要介紹嗎? – codeit 2013-02-09 04:04:36

+0

如果兩個事件A和B每個都有一個描述爲「帶傘」的提示,則自'A.id!= B.id.''提示表中將有兩個條目。 – tlehman 2013-02-09 04:06:48

回答

2

如果你想避免重複表條目,然後用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 

遷移來建立events_tips

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 2013-02-09 04:46:40