避免在ActiveRecord中存储重复的字符串

时间:2013-02-09 03:18:54

标签: mysql ruby-on-rails rails-activerecord

假设我有以下型号:

    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映射的情况下获得规范化的好处?

1 个答案:

答案 0 :(得分: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