Forum: Ruby on Rails Find not working

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
C728d93eb5205cf20cac0c2928b0ad62?d=identicon&s=25 Jeff Jones (Guest)
on 2006-02-28 00:33
Hello all.

I have the following code (taken from the depot tutorial then modified)

def add_dish( dish, type, qnty )
    item = @items.find {|i| i.dish_id == dish.id && i.type == type }
    if item
      item.quantity += qnty.to_i
    else
      if type == 'Fresh'
        item = Fresh.for_dish(dish)
      else
        item = Frozen.for_dish(dish)
      end
      item.order_id = 1
      item.quantity = qnty.to_i
      @items << item
    end
    @total_price += (dish.price * qnty.to_i)
  end


The problem line is this:

item = @items.find {|i| i.dish_id == dish.id && i.type == type }

It appears my simple addition has messed it up (Go me!). Simply put the
above never finds a match even when one is there. I am sure it is a
simple syntax problem but I am not sure what.

Could anyone answer the obvious and put me out of my misery :)

Thanks

Jeff
5d15c6821f3c3054c04b85471824ba7c?d=identicon&s=25 Roustem Karimov (Guest)
on 2006-02-28 04:30
(Received via mailing list)
On Tuesday, February 28, 2006, at 12:33 AM, Jeff Jones wrote:
>        item = Fresh.for_dish(dish)
>
>Thanks
>
>Jeff
>
>--
>Posted via http://www.ruby-forum.com/.
>_______________________________________________
>Rails mailing list
>Rails@lists.rubyonrails.org
>http://lists.rubyonrails.org/mailman/listinfo/rails

Jeff,

Just a guess... If this is a model object and "items" is defined via
"has_many" then you need to use "self.items" instead "@items".

Roustem
C728d93eb5205cf20cac0c2928b0ad62?d=identicon&s=25 Jeff Jones (Guest)
on 2006-02-28 09:46
>
> Jeff,
>
> Just a guess... If this is a model object and "items" is defined via
> "has_many" then you need to use "self.items" instead "@items".
>
> Roustem

@items is just an array setup like in the depot tutorial. There is no
model behind it.

class Cart
  attr_reader :items
  attr_reader :total_price

  def initialize
    empty!
  end

  def empty!
    @items = []
    @total_price = 0.0
  end

Jeff
This topic is locked and can not be replied to.