【问题标题】:Avoiding storing duplicate strings in ActiveRecord避免在 ActiveRecord 中存储重复的字符串
【发布时间】:2013-02-09 03:18:53
【问题描述】:

假设我有以下模型:

    class Event < ActiveRecord::Base
      has_many :tips
    end

    class Tip < ActiveRecord::Base
    end

提示描述只是 MySQL 数据库中的一个VARCHAR(140),其中大多数是固定值,例如“穿雨衣”或“带上支票簿”。我想使用规范化来避免存储大量具有相同值的字符串,但是,如果我将belongs_to :event 添加到Tip 模型中,event_id 值将导致许多重复提示。

如何在不手动管理tip_id &lt;---&gt; tip_description 映射的情况下获得规范化的好处?

【问题讨论】:

  • belongs_to 会如何导致重复?能介绍一下吗??
  • 如果两个事件 A 和 B 都有一个描述为“带伞”的提示,那么 tips 表中将有两个条目,因为 A.id != B.id。

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


【解决方案1】:

如果您想避免在表中重复输入,请使用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

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多