开发者

Pre-populate record with values from previous record [duplicate]

开发者 https://www.devze.com 2023-01-09 06:59 出处:网络
This question already has answers here: What is the easiest way to duplicate an activerecord record? (12 answers)
This question already has answers here: What is the easiest way to duplicate an activerecord record? (12 answers) Closed 2 years ago.

In a Ruby on Rails app I'm working on I have a Model that belongs_to a User. The User can create many of these.

W开发者_Go百科hen a user goes to the new action, I want to prepopulate the values with the values from the last record they created. These can then be changed if desired and used to create a new record.

I'm assuming that in the new action of my controller, I can get the most recent record (using something like this).

Model.first(:order => "created_at DESC")

Once I have that, how can I use it to pre-populate the record I created with the new method?


Can't you just initialize the attr?

class Model < ActiveRecord::Base
  def initialize_some_attr
    Model.first(:order => "created_at DESC").some_attr
  end
end


r = Model.first(:order => "created_at DESC")
n = Model.new(r.attributes)
0

精彩评论

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