假设我有以下模型:
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映射的情况下获得规范化的好处?
发布于 2013-02-09 12:16:39
如果您希望避免表中的重复条目,请使用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 << tiphttps://stackoverflow.com/questions/14784580
复制相似问题