I’m having trouble getting my view to render. I think I know why I’m getting the error:
undefined method `name' for nil:NilClass
Extracted source (around line #21): (showing 18-24)
<ul>
<%= form_tag(default_hero_user_path, :method=>'post') do %>
<%= label_tag "Name" %>
<%= text_field_tag "name", @user.default_hero.name %> #line 21
<%= submit_tag 'Set hero', class: "btn btn-large btn-primary" %>
<% end %>
</ul>
I know you can’t call .name on a nil object but I don’t understand why @user.default_hero is nil. I want the user to be able to set their ‘hero’ but having trouble setting the default obviously.
Here is the users controller:
# creates or updates the default hero
def default_hero
@user = User.find(params[:id])
hero = @user.default_hero
if hero.nil?
# we don't have a default hero so we need to add one'
hero = Hero.new
@user.heros << hero
end
hero.default = true
hero.name = params[:name]
hero.save
redirect_to @user # shows the user again to see any updates
end
And here is where I believe I am having the problem in setting a default view-
def show
@user = User.find(params[:id])
if @user.default_hero.nil?
name = params[:q]
else
name = @user.default_hero.name
end
Thanks for your guys’ time and attention if you can point me in the right direction in how to solve this I would ppreciated.
Your
showcontroller action doesn’t make much sense. You are setting a local variable (which won’t be accessible in the view) if@user.default_hero.nil?. This doesn’t accomplish anything and@user.default_herowill still benilin the view.That being said, to get rid of your error you can simply do this:
Based on your comment I would does something like this:
Model
Controller:
View:
You ignored my question about
params[:q], so I don’t know what to do with that.