避免存储重复的字符串

问题描述:

假设我有以下型号:避免存储重复的字符串

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

如果你想避免重复表条目,然后用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