Kevin Brown
Kevin Brown

Reputation: 12650

Rails Modify Array in Loop

I thought this would be a simple task, but I'm finding it difficult to make Rails do what I want.

I've got an array of dates.

So I thought that something like this would work:

  def index
    @datetimes = Books.all.map(&:checkouts).flatten.map(&:out_date)
    @datetimes.each do |c|
      c.to_date
    end
  end

Then I can just call this in my view:

%ul
[email protected] do |c|
    %li=c

How do I modify each key in the array? What am I missing here?

Thanks, so much for being nice to new, novice, and ignorant hobbyists like myself.

Upvotes: 0

Views: 391

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

.each doesn't modify the caller. It simply loops through. You could change the controller action to just this:

@datetimes = Books.all.map(&:checkouts).flatten.map{|e| e.out_date.to_date}

You might also want to explore including :checkouts in your Books query to avoid N+1 queries. Or perhaps doing something like this maybe.

Checkout.where("book_id is not null").map{|e| e.out_date.to_date}

Upvotes: 1

Related Questions