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.
<%= 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 %>
class Pledge < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end
class User < ActiveRecord::Base
has_many :pledges, foreign_key: "pledge_id"
accepts_nested_attributes_for :pledges
attr_accessor :pledges
end
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
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With