0

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?

2
  • 1
    I'm not sure what's going on here. Controllers aren't supposed to have an initialize method, and there's no need to use ActiveRecord::Base directly if you have a model. What reference are you basing this on? A good reference book on Rails should show you how to construct this properly. Commented Apr 26, 2016 at 3:12
  • I agree with @tadman, it is not a good idea for your controller to have an initialize method. Also, it looks like you are being redirected to "/results", I would either have your @results variable being defined in the results action, OR change your redirect_to '/results' to render :results. Commented Apr 26, 2016 at 16:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.