0

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.

1 Answer 1

1

.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}
Sign up to request clarification or add additional context in comments.

3 Comments

Philip...I'm ruby-novice level. I've heard of N+1 queries, but don't fully understand the concept. Can you elaborate? Should I move my nested model to a separate collection? Would that make things easier?
Additionally...I know this wasn't the original question. But what if I wanted to do math stuff to each value? Like add a year, or find the difference between that date and another?
@KevinBrown See guides.rubyonrails.org/… for info on N+1. If you want to do math to each value simply do it inside the last map{}. That is ...map{|e| (e.out_date + 1.year).to_date}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.