2012-03-25 134 views
0

我假設的很基本的Rails問題,但我無法弄清Rails的簡單性。Rails:爲相關模型創建動作

我的簡單目標是讓用戶提交一份表格,說明捐贈金額,並將捐贈鏈接到用戶。我在與在donations_controller.rb

create行動麻煩我有一個User.rb模型和Donation.rb模型。 User.rb has_one :donation和Donation.rb belongs_to :user。我也在使用Devise,所以我有current_user方法。

我的捐款表看起來像這樣

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.erbdonations_controller.rb看起來像這樣

<%= 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 

我得到這個錯誤m當我提交表單時發送消息。

NoMethodError in DonationsController#create 

undefined method `build' for nil:NilClass 

回答

0

用於構建HAS_ONE關聯的方法是current_user.build_donation(params[:donation])