PDF on ruby on rails

0

I have the following problem, I have a controller in which I make a query in which I get 10 different values each time I perform the query; but also at the same time I generate a pdf with wicked_pdf with the values with the values of the same query.

The problem I have is that when I render the data in my view, I want to generate a pdf with the same data, but when generating the pdf the data vary completely, that is, the query is executed again, How could this be avoided? ,

Controller

def index
  @test = Test.find_by(name: params[:test])
  @questions = TestQuestion.joins(:test).where(test_id:@test.id).order('RANDOM()').limit(10)
  respond_to do |format|
    format.html
    format.pdf { render template: 'simulators/pdf', pdf: 'pdf'}
  end
end

Agradesco in advance, any comment that can give me another approach to solve this problem

    
asked by Gerson 02.11.2018 в 00:08
source

1 answer

1

I think I know what the problem is. The detail is in .order('RANDOM()') every time you make a call to the controller method a new array is generated so you get different results. What you could do is change the RANDOM() for something more specific.

Or another option from the index method you get the IDs of the @question will pass it to a new route.

    def index
      @test = Test.find_by(name: params[:test])
      @questions = TestQuestion.joins(:test).where(test_id:@test.id).order('RANDOM()').limit(10)
      # Esta linea te regresara un arreglo con los puros IDS de la preguntas
      @question_ids = @questions.map{|question| question.id} 
    end

Create a new method in your controller that receives those IDs

  def to_pdf
    question_ids = params[:question_ids].to_a
    @questions = Question.where(id:@question_ids)
    respond_to do |format|
      format.pdf { render template: 'simulators/pdf', pdf: 'pdf'}
    end
  end

Add route

    get 'tests/to_pdf' => 'test#to_pdf', as:'test_to_pdf'

And finally add a button to your view that sends to that route

<%= link_to 'Descargar PDF', test_to_pdf_path(@question_ids) %>

In my opinion, this could work for you. But undoubtedly the easiest thing would be, as I told you at the beginning, to make the RANDOM() something more specific.

    
answered by 02.11.2018 / 02:24
source