0

我有一張配料表。當用戶輸入配料時,它會保存在表格中。現在我注意到很多記錄都是重複的,我不希望這樣,我想要的是如果這些記錄已經存在,那麼每個記錄都會被引用。如何存儲一次記錄並在其他表格中多次引用它?

因此,例如,我有面粉在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_createfirst_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 %> 
+0

在添加配料時查看自動完成解決方案。還要添加對成分名稱的唯一性驗證,以至少防止基於名稱的重複。 – jvnill 2013-03-28 01:22:16

+0

但如果我添加唯一性驗證用戶將保存一個已經存在的成分時出錯...也許我應該使用有一個而不是有很多?我現在要發佈我的模型。 – GiH 2013-03-28 01:26:30

+1

帶有自動完成解決方案,您不必擔心無法驗證唯一性。它只是在那裏,所以你不會在數據庫中有重複。如果它已經存在於數據庫中,那麼應該使用自動完成功能。如果沒有,那麼可以添加一個自由格式的文本字段,這將創建一個新的成分。 – jvnill 2013-03-28 01:36:10

回答

1

很難正是你需要的不知道看到一些代碼,但如果我理解正確,只要它不存在,就想創建一個成分。

查看導軌'dynamic finders。如果您使用的方法名稱,比如

@ingredient = Ingredient.find_or_create_by_name("flour") 

如果有之前的名稱爲「麪粉」的條目,將創建新的對象或返回稱爲「麪粉」現有的成分。在這兩種情況下,@ingredient都會持有上述聲明返回的所需條目。只有在Rails尚不存在的情況下,它纔會爲您創建它。

+0

那麼我如何使用視圖中的數據呢?用戶將傳遞參數params [:name]? – GiH 2013-03-28 01:39:21

+0

沒錯。只需傳入您需要的任何配料名稱即可。檢查你的params散列來得到確切的關鍵,但它會像'params [:name]'或者''params [:ingredient] [:name]''。 – weltschmerz 2013-03-28 01:42:10

+0

@GiH這樣做對你有用嗎?問題是否持續? – weltschmerz 2013-03-28 09:38:56

相關問題