Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How do I do nested forms with a has_one relationship?

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

Those are my relevant models. Any ideas? I kinda just need a good example.

like image 562
NullVoxPopuli Avatar asked Dec 30 '10 22:12

NullVoxPopuli


2 Answers

For Rails 4

Product Model

has_one                         :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for   :nutrition_fact

Nutrition Fact 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

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 %>
like image 62
drjorgepolanco Avatar answered Nov 07 '22 03:11

drjorgepolanco


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 to change your form as indicated in the step 2 of the link I provided.

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

like image 26
apneadiving Avatar answered Nov 07 '22 05:11

apneadiving