简体   繁体   中英

extract attributes values from an activerecord query object in rails 2.3

In my controller I have a @attach object and when I inspect it, it has values as

[#<MessageAddlAttachment id: 80, reminder_id: 112, msg_attachment_file_name: "24.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 272368, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">, #<MessageAddlAttachment id: 81, reminder_id: 112, msg_attachment_file_name: "37.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 333986, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">]

So now after some operation I need to create an entry in this MessageAddlAttachment table with different ids. How can I achieve it. I tried dup but it will have same ids. Please help

dup is your friend in rails 4. it will create a copy but removes the id value:

u = User.first
=> #<User id: 1, ...>
u.dup
=> #<User id: nil, ...>
u.dup.save
   (0.2ms)  begin transaction
...

Starting either rails 3.2 or 3.1, you want to use dup . Prior to that, you should use clone instead. That will give you new values for the id field; you might want to pay attention to what happens to your created_at and updated_at fields as well.

Another issue to watch out for is if you have any date fields with validations that say they must be after "today's date", they may have been valid when the original record was saved, but not when the new record is saved. How you resolve this will depend on your situation; you might want to disable validations completely while cloning, or adjust the values in the new records.

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