0

I just came across something that I have to do

find_or_create

or

where(attributes).first_or_create

as this post suggests.

But there's something I have been wondering

Is there an way to determine which action was triggered? (Because I want to display proper notice if it's created) BTW. I'm using Ruby 1.9.3

Thanks in advance.

Community
  • 1
  • 1
Firyn
  • 312
  • 3
  • 15

3 Answers3

1
if Model.find_by_attributes(attributes)
  flash[:notice] = "record found"
else
  Model.create(attributes)
  flash[:notice] = "record created"
end
shweta
  • 8,019
  • 1
  • 40
  • 43
  • thanks. I thought about using if else as well, but I'm kinda interested in finding out the action when use `find_or_create` or `first_or_create` – Firyn Jan 05 '13 at 05:00
1

My personal belief is not to use find_or_create, instead use find and create separately, that way I think its more cleaner and extendible.

As an example , if you want to do some more stuff after your record has been created. And I strongly believe in the concept of one method should do one thing :),

So I would write something like this

HTH

sameera207
  • 16,547
  • 19
  • 87
  • 152
  • I tried to use `__method__` as Michael suggested, but I'm kinda new to ruby and couldn't find a solution. I guess I probably just gonna go with shweta's answer. You do have a point. Thanks – Firyn Jan 05 '13 at 05:14
0

Use __method__ if ruby is 1.9.3+

if ['new','include'].include? __method__ then
  ...
else
  ...
end
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • It's you again Michael. Thanks for the answer, could you give me a bit more details on how to use it in the controller? – Firyn Jan 05 '13 at 04:57
  • thanks michael, now it seems like shweta's way is shorter. But I will keep this one in mind – Firyn Jan 05 '13 at 05:29