I have a User.rb model and a Donation.rb model. User.rb has_one :donation, and Donation.rb belongs_to :user.
I created a form whereby a donation gets linked to a user. In the console, I’m able to do this
ruby-1.9.2-p290 :003 > user.donation.amount
=> 1
Similarily, I’m able to do this on the views/users/show.html.erb
<p>Donation:<%= @user.donation.amount if @user.donation.amount? %></p>
However, in views/home/index.html.erb, I’m doing this
<h3>Home</h3>
<% @users.each do |user| %>
<p>User: <%=link_to user.name, user %></p>
<p>Email: <%= user.email if user.email %></p>
<p>Name:<%= user.name %></p>
<p>Donation:<%= user.donation.amount if user.donation.amount? %></p>
and getting this error
NoMethodError in Home#index
Showing /Users/michaeljohnmitchell/Sites/leafpledge/app/views/home/index.html.erb where line #6 raised:
undefined method `amount?' for nil:NilClass
I’m assuming this is because the association between User.rb and Donation.rb doesn’t work with the index action in the home_controller.rb because every user is being fetched rather than the particular user that I have in the views/users/show.html.erb.
def index
@users = User.all
end
Any idea how I can get it to work?
Your
ifcheck should be checking if the donation exists, not if the amount exists:Or, you could use the
trymethod which will avoid the undefined method error ifdonationis nil: