0

成分表があります。ユーザーが食材を入力すると、テーブルに保存されます。今、私が気づいているのは、多くのレコードが繰り返されていることです。私が望んでいるのは、これらの各レコードが既に存在する場合に参照されることです。

たとえば、小麦粉を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 %>
4

1 に答える 1

1

コードを見ずに何が必要かを正確に知ることは困難ですが、私の理解が正しければ、成分がまだ存在しない場合にのみ成分を作成する必要があります。

rails のdynamic finderをチェックしてください。次のようなメソッド名を使用する場合

@ingredient = Ingredient.find_or_create_by_name("flour")

以前に「小麦粉」という名前のエントリがない場合は新しいオブジェクトを作成するか、「小麦粉」と呼ばれる既存の成分を返します。どちらの場合も、@ingredient は、上記のステートメントによって返された目的のエントリを保持します。Rails は、まだ存在しない場合にのみ作成します。

于 2013-03-28T01:26:32.827 に答える