2012-03-25 8 views
0

かなり基本的なRails質問私は仮定しますが、Railsの単純さを理解することはできません。Rails:関連するモデルのアクションを作成します

私の単純な目標は、ユーザーに寄付金の額を示すフォームを提出させ、その寄付金をユーザーにリンクさせることです。 createアクションに問題がありますdonations_controller.rb

私はUser.rbモデルとDonation.rbモデルを持っています。 User.rb has_one :donationとDonation.rb belongs_to :user。私はcurrent_userメソッドを持っているので、Deviseも使用しています。

マイ寄付テーブルはdonations_controller.rbため、この

class CreateDonations < ActiveRecord::Migration 
    def change 
    create_table :donations do |t| 
     t.integer :amount 
     t.integer :user_id 

     t.timestamps 
    end 
    add_index :donations, [:user_id, :created_at] 
    end 
end 

_form.html.erbのように見えるがのように見えるこの

<%= form_for @donation do |f| %> 

    <div class="field"> 
    <%= f.number_field :amount %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Submit" %> 
    </div> 
<% end %> 

donations_controller.rbでcreateアクションはこの

def create 
    @donation = current_user.donation.build(params[:donation]) 
    if @donation.save 
     flash[:success] = "Donation" 
     redirect_to root_path 
    else 
     render 'home/index' 
    end 
    end 

Iのように見えますこのエラーが発生していますm私がフォームを提出するときに、エッセージ。

NoMethodError in DonationsController#create 

undefined method `build' for nil:NilClass 

答えて

0

has_oneの関連付けを構築するための方法は、current_user.build_donation(params[:donation])

あります
関連する問題