0

For simplicity, am using an easy example.

I have a controller method:

def test

  @books.each do |book|
    @book_id = "EMI:#{book.id}"
    @book_test = ....(some function)
  end

end

How do I pass the '@book_id' & '@book_test' values from the loop to the view page?

Please note that I don't want to repeat the code in the view page. Just want to pass the values in the loop to the view page.

6
  • I'm not sure how you want this to work, since you'll only get one @book_id variable (not one for each book)? Commented Apr 25, 2013 at 13:17
  • Andy is right, that loop will only give you the last book id. You should store the values to an array and iterate over it in the view. Commented Apr 25, 2013 at 13:20
  • It's not really clear to me what you're trying to do here. Can you expand a bit? Are you trying to render the view multiple times, or collect up a bunch of values to pass to the view? There's no sensible way to render a view inside a loop. Commented Apr 25, 2013 at 13:22
  • So there's no way of passing the values to the view after each loop? Commented Apr 25, 2013 at 13:22
  • @Tomanow in fact, you won't even be left with one variable (.each has separate scope, but a for loop wouldn't) ! Commented Apr 25, 2013 at 13:23

2 Answers 2

2

You have @books in the test method then why you are making your loop in that method? Do it in your view file directly no repetation needed.

Or other wise make two arrays like @book_ids and @book_tests and collect your prepared values and use them in your views like the following:

def test
@book_ids=[]
@book_tests=[]
@books.each do |book|
@book_ids << "EMI:#{book.id}"
@book_tests << ....(some function)
end
end
Sign up to request clarification or add additional context in comments.

1 Comment

It should be inside the test method. 'test' is a controller method :-)
1

Your controller takes unnecessary works it should have.

The jobs are better for Model, from what I've seen in the question

class Book < ActiveRecord::Base

  def book_id
    "EMI:#{self.id}"
  end

  def book_tests
    "some function"
  end
end

# Then in the view
@books.each |book| do
   book.book_id
   book.book_tests
end

Isn't this way cleaner?

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.