views:

47

answers:

1

Hello, I have problem with my associations. I have n:n relation and everything going good but if i want initialize new object and then save it, it will by save with out associations. For example.

Models:

class User
  has_many :users_in_organizations, :class_name => 'UserInOrganization'
  has_many :organizations,:through => :users_in_organizations
end 

#Attributes [:user_id, :organization_id, :user_role]
class UserInOrganization 
   set_table_name 'users_in_organizations'
   belongs_to :user
   belongs_to :organization
end

class Organization
  has_many :users_in_organizations, :class_name => 'UserInOrganization'
  has_many :users, :through => :users_in_organizations
end

this work fine but the problem is

org = User.first.organizations.new(:name => 'Test') #  new || build is the same
org.save # => true
User.first.organizations  # => []
Organization.all # => ['Test']

but if I use create then it works

org = User.first.organizations.create(:name => 'Test')
User.first.organizations  # => ['Test']
Organization.all # => ['Test']

Can anybody tell me what i am doing wrong?

Thank You :)

+2  A: 

If you want it working for new method, try this:

u = User.first
u.organizations.new :name => "new organozation"
u.save
u.organizations.size
=> 1

When you do org = User.first.organizations.new :name => "test" then you assign to org only organization and you save only that object. It doesn't save associated objects. That's why it doesn't work that way.

When you call create it saves created objects to db, using new or build doesn't save it to db.

klew