Newbie stuck again.. No errors, but my data won't save
has_many 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)%>
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 %>
精彩评论