I'm learning Rails building an ordering system and I'm stuck trying to build a form for Orders. Where Orders is a nested resource for Restaurant. Routes:
resources :restaurants do
resources :orders
resources :recipes
end
My models look like this:
class Restaurant < ActiveRecord::Base
has_many :orders
has_many :recipes, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes, dependent: :destroy
has_many :recipes, through: :order_recipes
end
class Recipe < ActiveRecord::Base
belongs_to :restaurant
has_many :order_recipes
has_many :orders, through: :order_recipes
end
My controller:
@recipes = @restaurant.recipes
@order_recipes = @recipes.map{|r| @order.order_recipes.build(recipe: r)}
And my view:
<%= form_for([@restaurant, @order]) do |order_form| %>
<%= order_form.label :Table_Number %>
<%= order_form.number_field :table_id %>
<%= order_form.fields_for :order_recipes, @order_recipes do |orf| %>
<%= order_form.hidden_field :recipe_ids %>
<%= order_form.label Recipe.where(id: :recipe_id) %>
<%= orf.number_field :quantity %>
My current problem is displaying the names of each recipe. It seems that :recipe_id is being passed as null all the time. My ultimate goal is to be able to build order_recipes populating the quantity column, and I thought having the recipe_id from order_recipes I could also access the correct recipe object from the DB to display the name or any other relevant data.