开发者

How to find a record that wasn't saved yet in Rails?

Say I have a record called Post that has many comments. Now I run the following code:

p = Post.new
p.comments.build(:title => 'great')

I would now like to locate that comment by its title. If the record was saved, I could do something like

p.co开发者_开发技巧mments.find_by_title('great')

But since it isn't saved yet, that's going to return nil (because it actually runs an SQL query) Is there a way to locate this record before it's saved?

Thanks!


comment = p.comments.build(:title => "great")


great_comment = p.comments.detect{|c| c.title == 'great'}


Just write:

new_comment = p.comments.build(:title => 'great')

and new_comment will be the newly added comment.

Or, you could do something like:

new_comments = p.comments.select{|x| x.new_record?}

which would give you an array with all the unsaved comments.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜