user1094757
user1094757

Reputation: 13

Rails 3 - Nested attributes and inheritance

Hy,

I have a problem in a nested form. Actually, I have two problems, but the second one is minor. The basic structure is like this :

class Connectable
  has_one :web_account
  accepts_nested_attributes_for :web_account
end

class Person < Connectable
end

class WebAccount
   belongs_to :owner, class_name => `Connectable`
end

And now, I would like to create a nested form to create a Person and a WebAccount at the same time. I have the following code :

<%= form_for @person do |f| %> 
   ...
   <%= f.fields_for web_accounts do |child| %>
      ....
   <end>
<end>

The only important attribute for WebAccount is name and is a string.

Note also the plural used in defining the child_form. I don't know why, but when I use a singular (which seems right to me), rails just prints out an empty form, while using a plural works just fine. I added some code in the controller to remplace the :web_accounts hash entry given by the form with :web_account.

More importantly, I get following error :

WebAccount(#97097470) expected, got ActiveSupport::HashWithIndifferentAccess(#83887850)

I also tried doing it in a console, defining following hash :

p = { :name => "ab", :lastname => "cd", :web_account => { :name => "ab.cd" }}

but with the same result.

Here is the code in my controller :

def create
  params[:person][:status] = Status.where(:name => params[:person][:status]).first

  # Transforms the web_accounts entry into web_account
  params[:person][:web_account] = params[:person][:web_accounts]
  params[:person].delete(:web_accounts)

  @person = Person.new(params[:person])

  .... (the rest is the standard response)

end

The error is given at line 58, which is the Person.new(...) line in the code above. I could print out the full framework trace if needed, but it is, as usual, rather long.

Why isn't this working? I just can't my head around it, as it seems to me that I have followed all the online tutorials... Could it the be the inheritance?

Upvotes: 1

Views: 360

Answers (1)

cutalion
cutalion

Reputation: 4394

You should use web_account_attributes instead of web_account. Docs

Try in the console:

p = { :name => "ab", :lastname => "cd", :web_account_attributes => { :name => "ab.cd" }}

Upvotes: 3

Related Questions