0

我想我可能在这里遗漏了一些东西,或者我对 Rails 模型关联的理解还不够(仍在学习中)。我有两个模型,一个配方和一个成分。食谱有很多成分,当我填写表格时,我想将食谱和成分参数发布到各自的数据库中

配方模型

 class Recipe < ActiveRecord::Base

 attr_accessible :dish_name, :country_of_origin, :difficulty, :preperation_time
 has_many :ingredients

 end

配料模型

 class Ingredient < ActiveRecord::Base
belongs_to :recipe
attr_accessible :ingredients
end

配方控制器

 def new 

 @recipe = Recipe.new

 end

 def create

 @recipe = Recipe.new(params[:recipe])
 if @recipe.valid?
 @recipe.save
 redirect_to recipes_path, :notice => "Recipe sucessfully created."
 else
 flash.now.alert = "Please ensure all fields are filled in."
 render :new

 end
end

配料控制器

  def new
  @ingredient = recipes.find(params[:recipes_id].ingredients.new
  @recipe_id = params[:recipe_id]
  end

形式

<%= form_for @recipe  do |f| %>

<%= f.label :dish_name, "Dish Name" %>
<%= f.text_field :dish_name, :placeholder => "Enter Dish Name" %>

more fields here(wanted to keep as short as poss)

<%= f.label :ingredients, "Ingredients" %>
<%= f.text_field :ingredients , :class => :ingred, :placeholder => "Enter Ingredient Here" %><br>
<% end %>

为代码的大小道歉,还有什么需要看看为什么我不能创建一个食谱吗?

4

2 回答 2

1

首先,您的成分模型是否包含像“recipe_id”这样的外键列?

此外,如果给定食谱的成分仅存储在单个文本字符串中,为什么不在食谱模型中将其作为一列而不是创建第二个模型呢?或者,如果您要将多种成分绑定到一个配方,您应该查看具有嵌套模型属性的表单。这里有一条很好的铁轨。

希望这可以帮助。

于 2012-11-03T00:45:54.693 回答
0

你的代码应该是链接这个...

- -楷模 - -

class Recipe < ActiveRecord::Base
 attr_accessible :dish_name, :country_of_origin, :difficulty, :preperation_time, :ingredients_collection
 has_many :ingredients
 def ingredients_collection
   self.ingredients.collect(&:name).join(" ,")  
 end
 def ingredients_collection(ingredients)
   ingredients.each do |ingredient|
   i = Ingredient.create(:name => ingredient)    
   self.ingredients << i
 end
 end
 end

class Ingredient < ActiveRecord::Base
  belongs_to :recipe
  attr_accessible :name # you should have some valid attribute name as it would conflict with the ingredients which is a method defined by the association (:has_many) in the instance of the Recipe...
  end

- - 控制器 - -

def new
 @recipe = Recipe.new
end
def create
  @recipe = Recipe.new(params[:recipe])
  if @recipe.save # no need to call the valid the validations would take care of it by themselves
    redirect_to recipes_path, :notice => "Recipe sucessfully created."
  else
    flash.now.alert = "Please ensure all fields are filled in."
    render :new
  end
end

无需为成分定义控制器...您将仅从配方实例中定义特定配方中的成分...

- -形式 - -

 <%= form_for @recipe  do |f| %>
   <%= f.label :dish_name, "Dish Name" %>
   <%= f.text_field :dish_name, :placeholder => "Enter Dish Name" %>
      more fields here(wanted to keep as short as poss)
   <%= f.label :ingredients, "Ingredients" %>
   <%= f.text_field :ingredients_collection , :class => :ingred, :placeholder => "Enter Ingredient Here" %><br>
  <% end %>

我仍然建议您研究虚拟属性,我想它会完全适合您的情况和需求......

http://railscasts.com/episodes/16-virtual-attributes了解虚拟属性

于 2012-11-03T05:33:56.697 回答