简体   繁体   中英

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?

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 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM