Ruby on Rails: How to insert nested forms with has_one relation?

class PollOption < ActiveRecord::Base belongs_to :poll has_one :address end class Address < ActiveRecord::Base belongs_to :user, :poll_options apply_addresslogic :fields => [[:number, :street], :city, [:state, :zip_code]] end 

These are my respective models. Any ideas? I just need a good example.

+4
source share
2 answers

This should answer:

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

The main idea is to declare accepts_nested_attributes_for :address in your PollOption model and change the form as indicated in step 2 of the link I provided.

Another useful link: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

+3
source

For Rails 4

Product model

 has_one :nutrition_fact, dependent: :destroy accepts_nested_attributes_for :nutrition_fact 

Actual Power Model

 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 

view / 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 %> 
+14
source

Source: https://habr.com/ru/post/1333854/


All Articles