I have Users and each user sets a Goal. So a goal belongs_to a user and a user has_one: goal. I am trying to use form_for in the view to allow the user to set their goal up.
I figured it would be like microposts (which is straight from Hartl’s tutorial) just with singular instead of plural. I’ve looked at tutorials and questions on here for this issue and tried numerous different things and I just can’t get it working.
I got the form_for actually working and apparently pointing to the correct route, but I’m getting the below error and I have no clue what it means:
undefined method `stringify_keys’ for “Lose Weight”:String
GoalsController
class GoalsController < ApplicationController
before_filter :signed_in_user
def create
@goal = current_user.build_goal(params[:goal])
if @goal.save
redirect_to @user
end
end
def destroy
@goal.destroy
end
def new
Goal.new
end
end
Goal Model
class Goal < ActiveRecord::Base
attr_accessible :goal, :pounds, :distance, :lift_weight
belongs_to :user
validates :user_id, presence: true
end
User Model
class User < ActiveRecord::Base
has_one :goal, :class_name => "Goal"
end
_goal_form (which is a modal on the Users#show)
<div class="modal hide fade in" id="goal" >
<%= form_for(@goal, :url => goal_path) do |f| %>
<div class="modal-header">
<%= render 'shared/error_messages', object: f.object %>
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>What's Your Health Goal This Month?</h3>
</div>
<div class="modal-body">
<center>I want to <%= select(:goal, ['Lose Weight'], ['Exercise More'], ['Eat Better']) %> </center>
</div>
<div class="modal-body">
<center>I will lose <%= select_tag(:pounds, options_for_select([['1', 1], ['2', 1], ['3', 1], ['4', 1], ['5', 1], ['6', 1], ['7', 1], ['8', 1], ['9', 1], ['10', 1]])) %> lbs. this month!</center>
</div>
<div class="modal-footer" align="center">
<a href="#" class="btn" data-dismiss="modal">Close</a>
<%= f.submit "Set Goal", :class => "btn btn-primary" %>
</div>
<% end %>
</div>
Routes.rb
resource :goal, only: [:create, :destroy, :new]
I expect the
stringify_keyserror is down to the way you’ve listed your options in the goal field, they need to be grouped up to be treated as one argument.Along with using
accepts_nested_attributes_for :goalas suggested by Dipak, you will want to have a nested form.The save action is now in the context of a user, so the attributes that come through will include a portion for the goal fields:
You can save these attributes by updating the user:
As an aside, your “new” action should be
@goal = Goal.new, just creating a new goal does nothing, you need to assign it to a variable for it to make it to the page.Good luck!