11
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.

2 Answers 2

31

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 %>
2
  • 2
    Nice answer, super useful! Oct 29, 2017 at 16:59
  • 3
    Beautiful, simple, useful answer. I've been searching for how to do this for over 2 hours and this hit the nail on the head. Jul 13, 2018 at 3:09
3

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.