Search code examples
ruby-on-railsactiverecordmany-to-manyhas-many-through

Rails BUILD method not saving association on has_many through


I have a Rails application setup as follows:

rails g model User name, password, etc....
rails g model Project title, description, etc....
rails g model Contract user:belongs_to project:belongs_to

rake db:migrate

Then in the console (Englishified for simplicity):

User.create!( params )
x = User.first.projects.build( params )
x.save
User.first.projects.to_a
[]
Project.first
[ project shows ]

The association on save is not working. Everything works just fine if I go directly with User.first.projects.create( params ) but this is not what I need.

What am I doing wrong?


Solution

  • You should save the User object after building a project to the user, but not the project object.

    If you save the project object after build only the Project will get created, but if you save the User object, the project will get assigned to the User.

    User.create!( params )
    
    user = User.first
    
    project = user.projects.build( params )
    
    user.save
    

    Now, you can check,

    User.first.projects.to_a
    
    [ project shows ]
    
    Project.first
    
    [ project shows ]