views:

114

answers:

2

Trying to perform a nested object form. The page loads with no errors, but when I send it, no information gets saved to the organization model.

The SQL call says this ..

Parameters: {"commit" => "save", "action"=>"update","_method"=>"put",  "organization"=>{"likes_snacks"=>"0"}, ..

Which is right. The 1 and 0 can be changed properly by flipping on and off the checkbox. But that information is just not saved to the database I guess. Any ideas?

HAML:

- form_for @user do |f|
  = f.label :username
  = f.text_field :username
.clear
  - fields_for :organization do |org| unless @user.organizations.empty?
    = org.label :likes_snacks, 'Like snacks?'
    = org.check_box :likes_snacks
= f.submit 'save', {class => 'button'}

CONTROLLER:

def edit
  @user = current_user
  @organization = current_user.organizations.first
end

MODELS:

ORGANIZATION.RB:

has_many  :users, :through => :organizations_users

USER.RB:

has_many  :organizations, :through => :organizations_users
+1  A: 

It seems like you can save the parent attributes but not the child attributes.

To make child attributes accessible through a nested forms you’ll need to add the “#{child_class_name}_attributes” to the attr_accessible method in your parent class.(Only if use attr_accessible in parent model)

So your parent model should look like this:

class User < ActiveRecord::Base
  attr_accessible :username, :organizations_attributes
  accepts_nested_attributes_for :organizations
end

Also, If you don’t use attr_accessible in your parent model this is not necessary.

randika
I don't use attr_accessible in my User mode. Are you saying that I don't need it then in my model?
Trip
Yah.. also why would :username be connected with :organizations_attributes, or more specifically, why does one attribute of User fall into organizations_attributes?
Trip
Ah gotcha. I forgot the s. This works! Thanks Randika
Trip
@Trip I'm glad it could help you.
randika
+1  A: 

I think the interesting part here is the linker table :organization_users.

The accepted answer on this so question says you need

form_for @user do |f|
  f.fields_for :organization_users do |ff|
    ff.fields_for :organization
Jesse Wolgamott
Ah! Well.. adding that f before fields_for helps. But I got this returned as an error ..unknown attribute: organization_usersand when I tried it my old way i got thisunknown attribute: organization
Trip
Using "field_for :organizations" (its plural), It returns this ActiveRecord::AssociationTypeMismatch in UsersController#updateOrganization(#24980000) expected, got Array(#101190)
Trip
Are you doing "ff.fields_for :organization" --- I think the double ff fixes the expectation problems.
Jesse Wolgamott