2010-12-30 5 views

Antwort

3

sollte diese Antwort:

http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

Die Hauptidee ist accepts_nested_attributes_for :address in Ihrem PollOption Modell zu erklären und Ihre Form zu ändern, wie in dem Schritt 2 des Link angezeigt I zur Verfügung gestellt.

Ein weiterer nützlicher Link: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+0

Ein weiterer nützlicher Link: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html – apneadiving

+0

Der Blog Link in erster Linie Adressen ' has_many' Beziehungen, anstatt 'has_one'. –

+0

@AndrewGrimm danke für Ihre Eingabe – apneadiving

13

Für Rails 4

Produkt-Modell

has_one       :nutrition_fact, dependent: :destroy 
accepts_nested_attributes_for :nutrition_fact 

Nutrition Fact Modell

belongs_to :product 

Products

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 

views/products/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 %> 
+0

Schöne Antwort, super nützlich! –