I think I may be missing something here or my understanding of rails model association isnt quite there yet (still learning). I have two models, a recipe and a ingredient. A recipe has many ingredients, and when i fill my form in i want to post recipe and ingredient params to their respective dbs
Recipe Model
class Recipe < ActiveRecord::Base
attr_accessible :dish_name, :country_of_origin, :difficulty, :preperation_time
has_many :ingredients
end
Ingredients Model
class Ingredient < ActiveRecord::Base
belongs_to :recipe
attr_accessible :ingredients
end
recipe controller
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
Ingredients Controller
def new
@ingredient = recipes.find(params[:recipes_id].ingredients.new
@recipe_id = params[:recipe_id]
end
Form
<%= 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 %>
Apologies for the size of the code, is anything else needed to see why i cannot create a recipe?
To start with, does your Ingredient model include a foreign key column like “recipe_id”?
Also, if the ingredients for a given recipe are just stored in a single text string, why not just make that a column in your recipe model instead of creating a second model? Alternatively, if you are going to have multiple ingredients tied to a single recipe, you should look into forms with nested model attributes. There’s a good rails cast on it here.
Hope this helps.