3

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

1
  • Does the User have any businesses yet? Commented Jun 9, 2013 at 19:46

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

7 Comments

So user would need to have a business first before the form is displayed? But what if I want user to input a business?
i was able to display the fields when I put <%= f.fields_for :businesses, @user.businesses.build do |field| %> But now when I save my database, the information doesn't show up in the field? Isn't my values should show up in the fields automatically if I want to edit my information? If I do <%= @user.businesses %> it shows my saved file.
And it just keeps adding new data when I try to insert more information into address and city field, Its supposed to override the original data?
I figured it out that I'm supposed to put the @user.businesses.build in my new action in users_controller
Found it : in a has_one relationship, it is @user.build_preferences. Found it thanks to this post: stackoverflow.com/questions/2472982/…
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.