Reputation: 29
Can anyone think of a reason why an instance variable declared in the controller would not be recognized by its view?
Controller looks something like this:
class UsersController < ApplicationController
...
def show
@questionshow = session[:profilequestioncapture]
@user = User.find(params[:id])
@question = Question.where("id = ?", @questionshow).first
...
And the view: (show.html.erb in the users directory:)
...
<dl class="dl-horizontal">
<dt>Headline</dt>
<dt>Description</dt>
<dt>Budget</dt>
<dd><%= @question.headline %></dd>
<dd><%= @question.description %></dd>
<dd><%= @question.currency %> <%= @question.budget %></dd>
</dl>
....
-the session correctly populates the @questionshow instance variable. It only contains the id, and this gets correctly passed to @question.
-here's what's strange: <%= @user.xxxx %> gets correctly formatted and displayed, whereas anything with <%= @question.xxx %> does not.
-and here's what's even stranger. If I comment out @user in the controller the record is still correctly displayed in the view, so it's effectively ignoring what's in the controller (but I can't figure out why)
-And yes I've checked I'm looking at the right controller & viewer.
Upvotes: 0
Views: 1427
Reputation: 29
I found the solution, but it's left me a bit bewildered. I was not defining the same instance variable attached to my Questions model across all actions in the same controller. So in Show is was @question whereas in Create it was (for example) @yyyquestion and in Update I had used something else (e.g. @yyyquestion). I have no clue why this would cause the error and why the instance variable would be populated in the controller but not in the View. I think there is more to this story...
Upvotes: 0
Reputation: 2495
First I think that the where scope will give you an ActiveRecord::Relation (which gives an array), not a record. Since you want to find by id I would suggest
Question.find(session[:profilequestioncapture])
Most probably you will want to rescue ActiveRecord::NotFound exception and either set a default question or change the behavior.
Are you using Draper or Presenters? Can you double check your @question actually has data?
As for your @user behind populated even if commented out:
Upvotes: 0
Reputation: 29599
@question
is an ActiveRecord::Relation
object. unless you call .first
on it, you'll have errors when you try to call some of the question attributes to it. and that will also be true if, as stated by one of the answers, session[:profilequestioncapture]
is nil
Upvotes: 0