1

I have on view show.html.erb

 <%= @question.user.lesson_id %>

and this is on browser a number.

my questions_controller.rb is

 def show
    @question = Question.find(params[:id])
    @comments = @question.comments.all
    if user_signed_in?
            @rating_currentuser = @question.ratings.find_by_user_id(current_user.id)
            unless @rating_currentuser
            @rating_currentuser = current_user.ratings.new
   end
 end

and my questions_controller_test.rb

   test "should show question signed in" do
    sign_in users(:user2)
    get :show, :id => @question_user1.to_param
    assert_response :success
   end

and everything is ok (browser and testing)

when change view show.html.erb

   <%= @question.user.lesson.name %>

I am OK with browser but fail testing with

   ActionView::Template::Error: undefined method `name' for nil:NilClass.

I try this

  @name = Lesson.find(params[:id])

on questions_controller.rb then test fail with

  Expected response to be a <:success>, but was <302>

similar questions here here and here

2 Answers 2

2

Using try can potentially mask the underlying problem.

For example, when I had this error it was because I wasn't creating a model object without the correct foreign key references fixed up - the view was rendering using the FK association with the name attribute - e.g. Product.ProductType.name. If I had used try to workaround it, it would have masked this fault in my test which would have been undesirable in the test. Once I had added the correct references everything worked as it should have with no need for try(:name).

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

1 Comment

Thank you for reply, in my schema.rb I have two tables. Table "lessons" with t.string "name" and table "tags" with t.string "name". Perhaps this is the issue. I try to change the database and see
1

The solution from this answer

is use the try method and change view as

<%= @question.user.lesson.try(:name) %>

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.