I find myself writing the following frequently:

r = MyActiveRecord.where(:attr1 => cond1, :attr2 => cond2, ...)
r.exists? ? r.first : r.create

... which has the effect of returning an instance of MyActiveRecord if
all the conditions are met, or creating one if it doesn't. A variant of
this:

c = MyActiveRecord.new(:attr1 => val1, :attr2 => val2, ...)
r = MyActiveRecord.where(:attr1 => c.attr1, :attr2 => c.attr2, ...)
c.save! unless r.exists?

... which has the effect of writing c to the db only if it is unique
across the given attributes.

Question: Do either of these forms replicate functionality already
provided by ActiveRecord? (I know about the find_or_create dynamic
methods, but those get unwieldy with more than two attributes.) Is
there a cleaner or more idiomatic way?

- ff

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

  • Michael Pavling at Jan 4, 2012 at 8:43 pm

    On 4 January 2012 20:25, Fearless Fool wrote:
    I find myself writing the following frequently:

    r = MyActiveRecord.where(:attr1 => cond1, :attr2 => cond2, ...)
    r.exists? ? r.first : r.create
    You want to look at the create_or_update_by_id and
    find_or_initialize_by_id methods :-)

    --
    You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
    To post to this group, send email to rubyonrails-talk@googlegroups.com.
    To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
    For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedJan 4, '12 at 8:26p
activeJan 4, '12 at 8:43p
posts2
users2
websiterubyonrails.org
irc#RubyOnRails

2 users in discussion

Fearless Fool: 1 post Michael Pavling: 1 post

People

Translate

site design / logo © 2021 Grokbase