简体   繁体   English

从rails 2.3中的activerecord查询对象中提取属性值

[英]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 在我的控制器中,我有一个@attach对象,当我检查它时,它的值为

[#<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. 所以现在经过一些操作后,我需要在这个带有不同id的MessageAddlAttachment表中创建一个条目。 How can I achieve it. 我怎样才能实现它。 I tried dup but it will have same ids. 我尝试过dup,但它会有相同的ID。 Please help 请帮忙

dup is your friend in rails 4. it will create a copy but removes the id value: dup是你在rails 4中的朋友。它将创建一个副本,但删除了id值:

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 . 启动rails 3.2或3.1,你想使用dup Prior to that, you should use clone instead. 在此之前,您应该使用clone代替。 That will give you new values for the id field; 这将为id字段提供新值; you might want to pay attention to what happens to your created_at and updated_at fields as well. 您可能还想注意您的created_at和updated_at字段会发生什么。

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. 您可能希望在克隆时完全禁用验证,或调整新记录中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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