SwordW SwordW - 7 months ago 5
HTML Question

How to put variables into HTML from ruby on rails

I tried to use a variable in HTML which is calculated from ruby code and MSSQL

This is my Ruby code to get @result

class StartingController < ApplicationController

before_action :require_user, only: [:index, :start]

attr_reader :table
attr_writer :table

def initialize
@table = Hash.new()
@connection = ActiveRecord::Base.connection
@st='exec search '
end

def start
.... some code set @st values
@result = @connection.exec_query(@st)
@table = @result[0]
redirect_to '/results'
end
end

def index
end

def results
end

end


This is the HTML which need to use @result

<% @result.each do |x| %>
<tr>
s: <td><%= x %></td>

</tr>
<% end %>


But I always get

undefined method `each' for nil:NilClass


if I

puts @result


I can get correct value

Can anyone help?

Answer

Problem is the instance variables(and variables) only accessible within an action, and your redirect_to actually change the action from start to results, so @results is not initialized.

I assume that you have a view at views/start/result.html.erb.

The best solution for this is you can remove the action results, and call render :results instead of redirect_to.

Comments