SwordW SwordW - 2 years ago 71
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 '

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

def index

def results


This is the HTML which need to use @result

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

<% end %>

But I always get

undefined method `each' for nil:NilClass

if I

puts @result

I can get correct value

Can anyone help?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download