The ''do'' block only executes if the find_or_initialize_by
method creates
the record.
The find_or_initialize_by method does not execute the ''do''
block if the
record exists.
Feature of Ruby that the ''do'' block goes to the method and the
method
must yield to execute the block.
Douglas Lovell
www.wbreeze.com
On 07/28/2012 02:19 PM, John Merlino wrote:> On the other forum on stackoverflow, someone provided this as a
> solution for the following use case: "I want to check by an unique ID
> whether a record is already created. If it is, I want to add 1 to the
> amount attribute. If it is not, I want to create it and set the amount
> attribute to 1."
>
> Here was their solution:
>
> @have = current_user.haves.find_or_initialize_by_id(params[:have]) do |
> h|
> h.amount = 0
> end
>
> I don''t think it''s a great one, but I have a question
about the block.
> Let''s say the record already exists and so the find is triggered
and
> when the record is queried, it has an amount value of 3. When that
> block is executed, it looks like the amount value would be assigned a
> value of 0. Or am I missing something?
>
--
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-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit https://groups.google.com/groups/opt_out.