Search code examples
ruby-on-railsvariableserbnomethoderror

No Method Error for Current User Variables in ERB


In my rails app I'm using erb to display an image of a blank checkbox if the user has not taken a certain quiz, but a checked box if they have. My if statement is:

<% if current_user.bal_code.nil? || current_user.flex_code.nil?%>
   <a href="app/views/users/show.html.erb"><%= image_tag "Checkbox Blank.png", class: "sf-checkbox", alt: "Blank Checkbox"%>
   <h5><strong>Step 4: <br class="xs-none"></strong>Finish Your Profile</h5></a>
<% else %>
   <%= image_tag "Checkbox Green.png", class: "sf-checkbox", alt: "Checked Checkbox"%>
   <h5><strong>Step 4: <br class="xs-none"></strong>Finish Your Profile</h5>
<% end %>

I get a no method error saying undefined method 'bal_code' for #<User:0x007fd7edc41040> for this if statement, but a previous if/else statement in which I used <% if current_user.gender.nil? %> worked perfectly fine. I'm not able to figure out why current_user.gender works, but current_user.bal_code is throwing up an error?

If it helps, this is in my application.html.erb code (it's on the footer of each page). Here are the appropriate database structures from my schema:

create_table "bal_quizzes", force: :cascade do |t|
  t.integer  "user_id"
  ...
  t.string   "bal_code"
end

add_index "bal_quizzes", ["user_id"], name: "index_bal_quizzes_on_user_id"

...

create_table "users", force: :cascade do |t|
  t.string   "name"
  t.string   "email"
  t.string   "password_digest"
  t.datetime "created_at",      null: false
  t.datetime "updated_at",      null: false
  t.string   "gender"
...
end

Can anyone help me with why I'm getting this error message?


Solution

  • You need to add an has_one method in your user model.

    More information about relationships:

    http://guides.rubyonrails.org/association_basics.html#the-has-one-association

    Edit:

    The bal_code attribute is only available in the bal_quiz model. So not on user.