开发者

In Ruby on Rails, how to solve User must have Address and Address must have User so they can't validate when saving?

开发者 https://www.devze.com 2023-02-15 17:24 出处:网络
For example, if the validation says a User must have an address (we separate address from the users table, if we allow 1 user to have as many addresses as needed associated with one user).

For example, if the validation says a User must have an address (we separate address from the users table, if we allow 1 user to have as many addresses as needed associated with one user). At the same time, the address must have a user (must belong to a user). So there is a user_id that points back to which user it is.

Then when you save the user or save the address, you can't because if you save a new user first, it can't point a valid address, bu开发者_如何学Ct if you save the address first, the user hasn't been saved -- so there is no id for a user record.

In such case, how do you handle it -- and is it the same in Rails 2.2 or 2.3 or 3.0? thanks.


Not 100% sure this will work but try something like this, using your original example.

@user = User.new

@user.build_address( pass params in here)

@user.save!

and vice versa..

0

精彩评论

暂无评论...
验证码 换一张
取 消