hellomello
hellomello

Reputation: 8597

nested attributes not displaying form correctly

I have a form from user

<%= form_for(@user) do |f| %>
  <%= f.fields_for :businesses do |field| %>
    <div class="field">
      <%= field.label :address %>
      <%= field.text_field :address %>
    </div>   
    <div class="field">
      <%= field.label :city %>
      <%= field.text_field :city %>
    </div>  
  <% end %>
<% end %>

It does not display my fields, but when i change businesses to business, then it shows, or if I remove the f from f.fields_for. But I don't think it properly saves into database.

my user model

class User < ActiveRecord::Base
  has_many :businesses
  accepts_nested_attributes_for :businesses
en

my business model

class Business < ActiveRecord::Base
  attr_accessible :user_id, :address, :city
  belongs_to :user
end

my bussiness migration

class CreateBusinesses < ActiveRecord::Migration
  def change
    create_table :businesses do |t|
      t.integer :user_id
      t.string :address
      t.string :city

      t.timestamps
    end
  end
end

Any suggestions as to what I'm doing wrong?

Thanks

Upvotes: 3

Views: 1872

Answers (1)

Tim Baas
Tim Baas

Reputation: 6185

You should build a business before it can display a form for it:

@user.businesses.build

Use that before using fields_for

Also check out this great gem for managing nested forms:

https://github.com/ryanb/nested_form

Upvotes: 7

Related Questions