0

In my rails app, I have a relation between User table (which is dedicated to authentication purpose) and Store table (which contains store information, like the name, description,...).

I mapped the two models like this:

  • User has_one :store

  • Store belongs_to :user

In the registration phase, I need to ask for both authentication information (I'm using Devise gem) like email and password, and the store name. This mean that I would like to fill two connected tables (User and Store) using the same form!

How does the ERB (or Haml) form looks like, especially for the Store Name part?

I tried this, but it doesn't work (more specifically, the line asking for store name):

= form_for(resources, :as => resource_name, :url => registration_path(resource_name)) do |f|
    = f.text_field :store[:name]
    = f.email_field :email
    = f.password_field :password
    = f.submit "Create"

Thanks in advance,

Hassen
  • 6,966
  • 13
  • 45
  • 65

1 Answers1

1

You can use fields_for:

= f.fields_for :store do |store_field|
  = store_field.text_field :name

And in your User model:

accepts_nested_attributes_for :store
Oscar Del Ben
  • 4,485
  • 1
  • 27
  • 41
  • Thanks for yor help Oscar, it works half! When I add `fields_for` the input is created. But when I add `accepts_nested_attributes_for :store` the input disappear!! I tried without the accepts_nested_attributes but I get MassAssignment error :/ – Hassen Aug 27 '12 at 15:09
  • You may have to replace :store with @user.store – Oscar Del Ben Aug 27 '12 at 15:57
  • The problem is that `@user` doesn't exist, because it's the registration page: `@user` and `@store` don't exist yet! – Hassen Aug 27 '12 at 20:17
  • What is resources? You need to have the relationship in the object in order to use fields_for. – Oscar Del Ben Aug 27 '12 at 22:31
  • I finally get it. This problem was solved in the following page http://stackoverflow.com/questions/4307743/profile-model-for-devise-users. Here, `resources` is generated by Devise gem to authenticate a user. – Hassen Aug 28 '12 at 08:36