私はUser.rbモデルとDonation.rbモデルを持っています。 User.rb has_one :donation
、Donation.rb belongs_to :user
。Rails:インデックスアクションのfind.allで関連付けを使用する
寄付がユーザーにリンクされるようなフォームを作成しました。コンソールでは、私はこの
ruby-1.9.2-p290 :003 > user.donation.amount
=> 1
と似て操作を行うことができるよ、私は、views/home/index.html.erb
に、しかしビュー/ユーザー/ show.html.erb
<p>Donation:<%= @user.donation.amount if @user.donation.amount? %></p>
でこれを行うことができますよ私は、このエラー
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
この
<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>
をやって取得しています
これは、のユーザーが私が所有している特定のユーザーではなくフェッチされているため、User.rbとDonation.rbの間の関連付けがhome_controller.rbのインデックスアクションで機能しないためですviews/users/show.html.erb
。
def index
@users = User.all
end
私はどのように動作させることができますか?寄付が存在する場合