Pretty basic Rails question I assume but I can’t figure out the simplicity of Rails.
My simple goal is to have a user submit a form indicating the amount of a donation, and have that donation linked to the user. I’m having trouble with the create action in the donations_controller.rb
I have a User.rb model and a Donation.rb model. The User.rb has_one :donation and Donation.rb belongs_to :user. I am also using Devise so I have the current_user method.
My donation table looks like this
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
The _form.html.erb for the donations_controller.rb looks like this
<%= form_for @donation do |f| %>
<div class="field">
<%= f.number_field :amount %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
The create action in donations_controller.rb looks like this
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 getting this error message when I submit the form.
NoMethodError in DonationsController#create
undefined method `build' for nil:NilClass
The method for building the has_one association is
current_user.build_donation(params[:donation])