Is there any ActiveRecord's dynamic finder that can allow me to find first association or create it if it doesn't exist. Something like this (not this code is conceptual - it does not work!):
Comment.posts.find_or_create(:first)
Is there any ActiveRecord's dynamic finder that can allow me to find first association or create it if it doesn't exist. Something like this (not this code is conceptual - it does not work!):
Comment.posts.find_or_create(:first)
Milan Dobrota wrote:
Is there any ActiveRecord's dynamic finder that can allow me to find first association or create it if it doesn't exist. Something like this (not this code is conceptual - it does not work!):
Comment.posts.find_or_create(:first)
I meant:
Post.comments.find_or_create(:first) lol
Well, this is strictly off the top of my head, but could you:
@post = Post.find(...somehow...)
Comment.find_or_create_by_post_id(:post_id => @post.id)
If that doesn't do what you want, post more code that shows what you want and what you've tries that is giving you a different result.
-Rob
Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com
If it doesn't find a comment, and creates a new one, what values is it going to populate the record with? Or is it that you want a new blank record for some purpose?
Either that or perhaps to be able to use the find_or_initialize counterpart.
In this case I have before create hooks in place to fill in some attributes.
If you trim the whole of the email you're replying too, we lose all sense of context....
Anyway... a simple solution is to have a method add a new comment if the comments array is empty, and then send the call that you pass to the array (so you can use any Array method as a parameter). More complex solutions would be to patch AR::Base or maybe Array to do a similar thing.
# in your Post model def find_or_create_comment(which) Post.comments << Comment.create if Post.comments.blank? Post.comments.send(which.to_s) if Post.comments.respond_to?(which.to_s) end
That's off the top of my head so it is probably buggy, but might put you on the tail of something that suits - it relies on the "create" method actually working, so if the Comment fails validation, it will break big time.
I think better solutions might be suggested if you describe the problem that you have that you want to use this as a solution to...
Regards,