0

私は今、この1つの問題に何日も悩まされています。これは私にとって初めての Rails アプリであり、ほぼ完成に近づいていますが、これによってかなり遅くなるだけです。

accept_nested_attributes_for を使用することが、フォームで使用するために Recipe 内で Ingredients をネストするという私の問題に対する最良の解決策であると読みましたが、これまでのところ運がありませんでした。この件に関して見つけられるものはすべて読みました。API によると、モデルには (私の場合は) components_attributes= メソッドが含まれるようになりましたが、まだ表示されていません。コンソールでハッシュを使用して update_attributes を使用しようとしました

recipe.update_attrubutes {:ingredients_attributes=>[{:name=>"Test Ingredient"}]}

これはtrueに戻りますが、レシピ オブジェクトに変更はありません。

私は多くのアプローチを試みましたが、最初は、View 内の forms_for 内で fields_for を使用するだけです。これが機能せず、コードを無駄にテストしていたので、より深く調べ始めたところ、問題は間違いなくビューよりも深刻です。

どんな助けでも大歓迎です。私のコードは次のとおりです

レシピモデル

db スタイルの名前と表示スタイルの名前の変換が混乱していて申し訳ありません。これは、両方を維持するためのこれまでの私の最善の修正です。

class Recipe < ActiveRecord::Base

  DISH_TYPES={""=>"", "Breakfast"=>"breakfast", "Lunch"=>"lunch", "Soup"=>"soup", "Entree"=>"entree", "Desert"=>"desert"}
  SEASONS={"Any Season"=>"any", "Fall"=>"fall", "Winter"=>"winter", "Spring"=>"spring", "Summer"=>"summer"}
  DIETS={""=>"", "Vegan"=>"vegan", "Vegetarian"=>"vegetarian", "Omnivore"=>"omnivore"}

  DISH_TYPES_R={""=>"", "breakfast"=>"Breakfast", "lunch"=>"Lunch", "soup"=>"Soup", "entree"=>"Entree", "desert"=>"Desert"}
  SEASONS_R={"any"=>"Any Season", "fall"=>"Fall", "winter"=>"Winter", "spring"=>"Spring", "summer"=>"Summer"}
  DIETS_R={""=>"", "vegan"=>"Vegan", "vegetarian"=>"Vegetarian", "omnivore"=>"Omnivore"}

  attr_protected :user_id
  # Do NOT include user_id in the attr_accessible method, to avoid
  # the possibility of it being changed externally.
  belongs_to :user
  validates_presence_of :user  
  has_many :ingredients, dependent: :destroy # , inverse_of: :recipe

  # Allows for forms to write attributes down the hierarchy.
  accepts_nested_attributes_for :ingredients, allow_destroy: true , reject_if: lambda { |a| a[:content].blank? }

  before_save do
    # Lowercase and convert to strings all of the attributes
    # that require a specific format, namely the values in the
    # constant hashes above.
    STRING_ATTRIBUTES.each do |s|
      self.send("#{s}=".to_sym, self.send(s).downcase.to_s)
    end
  end

  validates :user_id, presence: true
  validates :name,  presence: true,
                    length: { maximum: 64 } #,uniqueness: true
  validates :dish_type, inclusion: { in: DISH_TYPES.values }
  validates :season, inclusion: { in: SEASONS.values }
  validates :diet, inclusion: { in: DIETS.values}
  validates :directions,  presence: true,
                          length: { maximum: 8192 }

  validates_associated :ingredients


  default_scope order: "recipes.created_at DESC"


  def method_missing (method)
    method = method.to_s
    if method.slice!("display_")
      if STRING_ATTRIBUTES.include?(method.to_sym)
        hash_name = method.upcase + 'S_R'
        Recipe.const_get(hash_name)[self.send(method.to_sym)]
      else
        method
      end
    else 
      method.class
    end
  end

  private

    STRING_ATTRIBUTES = [:dish_type, :season, :diet]

end

成分モデル

class Ingredient < ActiveRecord::Base

  attr_protected :id, :recipe_id
  belongs_to :recipe

  validates_presence_of :name
  #validates_presence_of :recipe
end

レシピコントローラー

コントローラーで何も変更する必要はないことを読みました。Ingredient フォームがビューに表示されるように、1 行だけ追加しました。

class RecipesController < ApplicationController
  before_filter :signed_in_user, only: [:create, :edit, :destroy]

  def index
    @recipes = Recipe.all
  end

  def new
    if signed_in?
      @recipe = current_user.recipes.build 
      @recipe.ingredients.build
    else
      flash[:error] = "First you have to register! Sign up here and start adding recipes ASAP."
      redirect_to signup_path
    end
  end

  def create
    @new_recipe = current_user.recipes.build(params[:recipe])
    if @new_recipe.save
      flash[:success] = "You've successfully added #{@new_recipe.name}!"
      redirect_to @new_recipe
    else
      redirect_to 'new'
    end
  end

  def edit
    @recipe = Recipe.find(params[:id])
  end

  def show
    @recipe = Recipe.find(params[:id].to_i)
  end

end

成分コントローラー

材料は(今のところ)親のレシピからのみアクセスされるため、材料コントローラの用途はないと思います。

リクエストがあれば意見を含めますが、前述したように、それほど高いレベルではないと思います。

4

1 に答える 1

1
  1. モデルを設定attr_accessibleしてRecipeそこに追加する必要があります:ingredients_attributes
  2. 私があなたの設定で見るように、あなたはreject_if: lambda { |a| a[:content].blank? }ingrediens_attributesのために持っていて、あなたはそれを名前だけで設定しています
于 2012-12-28T04:39:37.887 に答える