для рельсов 4
Модель продукта
has_one :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for :nutrition_fact
Модель факта питания
belongs_to :product
ProductsController
def new
@product = Product.new
@product.build_nutrition_fact
end
def edit
@product.build_nutrition_fact if @product.nutrition_fact.nil?
end
private
def product_params
params.require(:product).permit(:title, :price, nutrition_fact_attributes: [:serving_size, :amount_per_serving, :calories])
end
Вид / произведения / new.html.erb
<%= form_for @product do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= f.fields_for :nutrition_fact do |fact| %>
<%= fact.label :serving_size %>
<%= fact.text_field :serving_size %>
<%= fact.label :amount_per_serving %>
<%= fact.text_field :amount_per_serving %>
<%= fact.label :calories %>
<%= fact.text_field :calories %>
<% end %>
<%= f.submit "Create Product", class: "example-class" %>
<% end %>