我有一張配料表。當用戶輸入配料時,它會保存在表格中。現在我注意到很多記錄都是重複的,我不希望這樣,我想要的是如果這些記錄已經存在,那麼每個記錄都會被引用。如何存儲一次記錄並在其他表格中多次引用它?
因此,例如,我有面粉在DB中保存了大約20次。我希望將它保存一次,對於每個配方,當用戶輸入麪粉時,應該只在數據庫中引用該配料。我如何實現這一目標?
我已經有一個Entry模型(配方)和一個連接EntryIngredient模型。因此,無論何時一個Entry保存一個已經存在的成分,我都希望它只是在EntryIngredient表中引用那個(作爲外鍵),而不是創建一個新的。
class Ingredient < ActiveRecord::Base
has_many :entry_ingredients
has_many :entries, :through => :entry_ingredients
end
class EntryIngredient < ActiveRecord::Base
belongs_to :entry
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
class Entry < ActiveRecord::Base
belongs_to :user
has_many :entry_ingredients
has_many :ingredients, :through => :entry_ingredients
has_many :steps
accepts_nested_attributes_for :entry_ingredients, :allow_destroy => true
accepts_nested_attributes_for :steps, :reject_if => lambda { |s| s[:description].blank? }, :allow_destroy => true
end
UPDATE:
動態查找聽起來像他們做我想做的,特別是find_or_create
或first_or_create
但我無法弄清楚如何在我的設置中使用它們。任何人都可以把我推向正確的方向嗎?這是我做過嘗試,但我知道,這僅僅是創建一個新的成分,每當#新的條目被稱爲......不是我希望發生
#entries_controller.rb
def new
@entry = Entry.new
@entry.entry_ingredients.build.build_ingredient
@entry.steps.build
@ingredient = Ingredient.where(params[:ingredient]).first_or_create()
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @entry }
end
end
#_entry_ingredient_fields.html.erb
<%= f.fields_for :ingredient do |builder| %>
<%= builder.label :name %>
<%= builder.text_field :name, :class => "ingredient_field" %>
<% end %>
在添加配料時查看自動完成解決方案。還要添加對成分名稱的唯一性驗證,以至少防止基於名稱的重複。 – jvnill 2013-03-28 01:22:16
但如果我添加唯一性驗證用戶將保存一個已經存在的成分時出錯...也許我應該使用有一個而不是有很多?我現在要發佈我的模型。 – GiH 2013-03-28 01:26:30
帶有自動完成解決方案,您不必擔心無法驗證唯一性。它只是在那裏,所以你不會在數據庫中有重複。如果它已經存在於數據庫中,那麼應該使用自動完成功能。如果沒有,那麼可以添加一個自由格式的文本字段,這將創建一個新的成分。 – jvnill 2013-03-28 01:36:10