成分表があります。ユーザーが食材を入力すると、テーブルに保存されます。今、私が気づいているのは、多くのレコードが繰り返されていることです。私が望んでいるのは、これらの各レコードが既に存在する場合に参照されることです。
たとえば、小麦粉をDBに約20回保存しました。一度保存して、レシピごとに、ユーザーが小麦粉を入力したときに、DB でその材料を参照するだけでいいのです。どうすればこれを達成できますか?
Entry モデル (レシピ) と Join EntryIngredient モデルが既にあります。したがって、 Entry が既に存在する Ingredient を保存するときはいつでも、新しいものを作成するのではなく、 EntryIngredient テーブル内のその 1 つを (外部キーとして) 参照するだけにしたいと考えています。
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
アップデート:
動的ファインダーは、具体的には私が望むことをしているように聞こえfind_or_create
ますfirst_or_create
が、私のセットアップでそれらを使用する方法を理解することはできません. ここで誰かが私を正しい方向に押し進めることができますか? これは私が試したことですが、これはエントリ#newが呼び出されるたびに新しい成分を作成しているだけであることに気付きました...私が望んでいることではありません
#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 %>