Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `build' for nil:NilClass rails

What I think is going on is that the :pledge attributes (:amount and :frequency)from my view is not getting passed to the new action in the controller. Also, I know that my pledge attributes are not saving and maybe that's because pledge_id is nil when calling @user.

new.html.erb

<%= form_for @user, url: pledge_path, controller: 'user', action:     'create', method: 'post' do |f| %>
  <%= f.label :user_name %>
  <%= f.text_area :user_name %>
  <%= f.label :email %>
  <%= f.text_area :email%>
  <%= f.label :address %>
  <%= f.text_area :address %>
  <%= f.fields_for(:pledge) do |b| %>
    <%= b.label :amount %>
    <%= b.text_area :amount %>
    <%= b.label :frequency %>
    <%= b.text_area :frequency %>
    <%= b.submit 'I also want o pledge' %>
  <% end %>
<%= f.submit 'I just want to sumbit my info' %>

<% end %>

pledge.rb

class Pledge < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user

end

user.rb

class User < ActiveRecord::Base
  has_many :pledges, foreign_key: "pledge_id"
   accepts_nested_attributes_for :pledges
   attr_accessor :pledges

end

schema.rb

ActiveRecord::Schema.define(version: 20150318161827) do

create_table "pledges", force: :cascade do |t|
  t.integer "frequency"
  t.float   "amount"
  t.integer "user_id"
end

add_index "pledges", ["user_id"], name: "index_pledges_on_user_id"

create_table "users", force: :cascade do |t|
  t.string  "user_name"
  t.string  "email"
  t.string  "address"
  t.integer "pledge_id"
end

end

user_controller.rb

class UserController < ApplicationController
def new
    @user = User.new
    @user.pledges.build 
end

def create
    if params[:commit] == 'I just want to sumbit my info'
        User.create(user_params)

    elsif
        @pledge = Pledge.new(params[:pledge])
        @pledge.save
        @user = User.create(pledge_params)  
    end
    redirect_to thank_you_path

end
def pledge_params
    params.require(:user).permit(:email, :user_name, :address,
                                pledge_attributes: [:id, :amount, :frequency])
end

def user_params
    params.require(:user).permit(:email, :user_name, :address)
end
end

Thanks in advance for any suggestions!

like image 895
K Waters Avatar asked Mar 18 '15 18:03

K Waters


1 Answers

Info from here was helful for me in similar case like yours.

So in code of Sontya you need to change @user.pledges.build to @user.build_pledges.

Although, i think you solved your issue, but i do this answer to help anyone who will search this info.

like image 157
Maxim Kholyavkin Avatar answered Sep 19 '22 13:09

Maxim Kholyavkin