Reputation: 53
I have been searching through Stack Overflow for a few hours now, but none of the related questions seem to apply to my issue.
I am new to Rails, with this being my first real project, and I may be confusing the MVC setup a little. I am attempting to assign the @stars instance variable while in an action of the searches_controller.rb:
def create
@search = Search.new(params[:search])
tempstr = searchstr(@search)
@stars = Star.where("tempstr", :limit => 100)
end
@search
is created fine, being a complex search with varying parameters. tempstr
is just a simple string container for the results of searchstr(@search)
, which is a quick method for converting the search parameters into a MySql-relevant string (which seems to be easier than trying to use the .where helper normally, in this case). I'm sure I can just put searchstr(@search)
directly into the .where, but I split them up for now so I can inspect the elements as they pass through.
Anyways, the issue comes up when I try to call @stars
in the show.html.erb view. Even with something as simple as this:
<% @stars.each do |star| %>
<%= display stuff %>
<% end %>
I get an error saying 'each' is not a method of nil:NilClass
. So, I changed it to the following to see if @stars was nil:
<%= @stars.inspect %>
Sure enough, @stars
is nil
. However, when I add this line to my controller to check @stars
there:
return render @stars.each
I see that the variable is filled with the correct star objects from the Star.where(), just as I had intended. A quick .inspect shows the variable is not nil, when in the controller.
So, I am unsure why the view is receiving it as nil if it has been defined in the controller just fine. I wouldn't be surprised if it was me misunderstanding how MVC works, though. The Star class was defined in the Star model, but maybe it is because I am trying to access it from the Searches controller, and thus it isn't initialized for the view?
Should I be going about doing this some other way? I attempted to use a local variable (using stars
instead of @stars
), but then the view says "Undefined local variable or method 'stars'".
Any help would be much appreciated, I have already wracked my brain for hours creating the complex search and parsing the star file data into the database, so I'm a bit burnt out. I can supply more information if requested, I'm not sure what else would be helpful in providing an answer.
Upvotes: 5
Views: 1787
Reputation: 43298
You are setting @stars
in the create
method, but the view you are talking about is show.html.erb. Try setting @stars
in the show
method too. Something like this:
def show
@search = Search.find(params[:id])
tempstr = searchstr(@search)
@stars = Star.where("tempstr", :limit => 100)
end
If this does not help you, please show the rest of you controller actions, so we can help you better.
Upvotes: 3