假设我有以下型号:
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 :(得分: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