purpletonic
purpletonic

Reputation: 1878

Rails nested forms with has_one through relations

I'm really struggling to understand how to create a nested form with a model connected by a second model. I've looked up a number of posts on SO, and tried many approaches, but can't figure it out, though I think I'm almost there.

I'm trying to create a subscription, customer and the customer's address in the one form but so far I've only managed to create the subscription and customer. I'm having problems with the address.

A customer can have many subscriptions, but only the one address (for the time being, anyway)

My (abbreviated) code looks like the following:

subscription.rb

class Subscription < ActiveRecord::Base

  belongs_to :customer
  has_one :address, through: :customer

  accepts_nested_attributes_for :customer, :address
  attr_accessible :customer_attributes, :address_attributes

customer.rb

class Customer < ActiveRecord::Base

  has_one :address
  has_many :subscriptions

  accepts_nested_attributes_for :address
  attr_accessible :address_attributes

address.rb

class Address < ActiveRecord::Base

  belongs_to :customer
  has_many :subscriptions, through: :customer

subscriptions_controller.rb

def new
  @subscription = Subscription.new    
  customer = @subscription.build_customer
  address = customer.build_address
  subscription_line_items = @subscription.subscription_line_items.build
end

subscriptions/_form.html.erb

<%= form_for(@subscription) do |subscription_form| %>
  <% if @subscription.errors.any? %>
    <!-- Error stuff -->
  <% end %>

  <div class="field">
    <%= subscription_form.label :start_date %><br />
    <%= subscription_form.text_field :start_date %>
  </div>

  ...

  <h2>Customer Details</h2>
  <%= subscription_form.fields_for :customer do |customer_fields| %>
    <%= customer_fields.label :first_name %><br /> 
    <%= customer_fields.text_field :first_name %>
    ...
  <% end %>

  <h2>Address</h2>
  <%= subscription_form.fields_for :address do |address_fields| %>
    <%= address_fields.label :address_1 %><br /> 
    <%= address_fields.text_field :address_1 %>
    ...
  <% end %>

  <div class="actions">
    <%= subscription_form.submit %>
  </div>
<% end %>

I know that my controller code is working, as when I try it directly in the console, I get an empty address object, but this isn't being rendered in the form, which leads me to believe my model code still isn't correct.

Upvotes: 0

Views: 743

Answers (1)

Hugo
Hugo

Reputation: 2129

Purpletonic, looking your latest problem about:

Can't mass-assign protected attributes: customer, address

you need to add those attributes in your model like:

attr_accessible :customer, :address

Upvotes: 1

Related Questions