views:

60

answers:

1

http://stackoverflow.com/questions/1993615/hasmany-build-method-rails

Was my last question. It now works: no errors. The new problem is that the new unit conversion doesn't associate with an ingredient ID. I thought this was "just supposed to work" from the build method?

Unit Conversion controller:

 def new
  @ingredient = Ingredient.find(params[:ingredient_id])    
  @unit_conversion = @ingredient.unit_conversions.build
end

def create
  @ingredient = Ingredient.find(params[:ingredient_id])    
  @unit_conversion = @ingredient.unit_conversions.build(params[:unit_conversion])

  if @unit_conversion.save
    flash[:notice] = "Successfully created unit conversion."
    redirect_to ingredient_unit_conversions_url(@ingredient)
  else
    render :action => 'new'
  end
end

Unit Conversion Model:

class UnitConversion < ActiveRecord::Base
  belongs_to :ingredient
end

Ingredient Model:

class Ingredient < ActiveRecord::Base
  belongs_to :unit
  has_many :unit_conversions
end

Thanks for the help, I'm finding a rough learning curve today :)

EDIT: One more important thing.. new.html.erb

<h1> New Derived Unit </h1>
<% form_for([@ingredient, @unit_conversion]) do |f| %>
        <% f.error_messages %>

        <p>
            <%= f.label :name %>
            <%= f.text_field :name%>
        </p>
        <p>
            <%= f.label :conversionToBase%>
            <%= f.text_field :conversionToBase%>
        </p>
        <p>
            <%= f.submit "Create" %>
        </p>
    <% end %>
<% link_to 'Back', url_for( :controller => 'ingredients', :action => 'show', :id => @ingredient)%>
+2  A: 

Make sure that you have form_for [@ingredient, @unit_conversion] in your form.

new.html.erb

<% title "New Unit Conversion" %>
<%= render :partial => 'form' %>
<p><%= link_to "Back to List", ingredient_unit_conversions_path(@ingredient) %></p>

_form.html.erb

<% form_for [@ingredient, @unit_conversion] do |f| %>
  <%= f.error_messages %>
  <p>
  ... fields here
  </p>
  <p><%= f.submit "Submit" %></p>
<% end %>
Chandra Patni
I Guess I wasn't quite clear. The data entered in the form saves to the table, but the ingredient_id does not. I edited the post after you answered to show new.html.erb. I think I have this already in the file..
Joan