0

古いユーザー オブジェクトと新しいユーザー オブジェクトがあります。新しいユーザー オブジェクトを作成しようとしていますが、すべての属性を古いユーザー オブジェクトに割り当て、ユーザー テーブルに新しい行を作成せずに ID (主キー) を同じに保ちたいと考えています。

old_user = User.find(20)
old_user.id # this is 20
old_user.name # this displays "old_name"
new_user = User.new
new_user.name = "new_name"
old_user = new_user
old_user.save # this doesn't work since the new_user.id is nil and so is old_user.id is nil
old_user.id = 20 and save #this won't work either.

new_user の状態を old_user オブジェクトに保存し、同じ主キー ID を維持するにはどうすればよいですか。

4

3 に答える 3

0

あなたの質問に答えるのはとても簡単ですが、Zach Kemp が上で言ったように、ユースケースを説明する必要があります。

とにかく、これはあなたが望むことをします。

old_user = User.find(20)
new_user = User.new(old_user.attributes)
new_user.save!
于 2012-10-19T21:35:15.120 に答える
0

これが必要な場合は、Ruby の clone メソッドが役に立ちます。また、IDのクローンを作成します

new_user = old_user.clone
于 2012-10-20T11:28:42.403 に答える
0

あなたの質問からわかる限り、新しいユーザー オブジェクトは必要ありません。ActiveRecord オブジェクトの属性を更新するには、いくつかの方法があります。

user = User.find(20)
user.name = "new_name"
user.save # returns true if successful

ハッシュを渡して、複数の属性を一度に更新できます。

user = User.find(20)
user.update_attributes(name: "new_name", email: "new_email@email.com")
于 2012-10-19T20:56:44.333 に答える