Reputation: 453
I am having a weird issue that I can't figure out.
It is very basic rails programming : I want to create an association between a user model and a goal model.
goal.rb
class Goal < ActiveRecord::Base
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
has_many :goals, dependent: :destroy
has_many :records
has_many :orders
end
When I am making the association from the console, it is working well, lets say :
$ goal = Goal.first
$ goal.user_id = 1
$ goal.save
$ goal.inspect
#<Goal id: 1, description: "loremipsum", created_at: "2016-11-26 12:39:34", updated_at: "2016-11-26 12:43:41", name: "ipsumlorem", user_id: 1>
But then, when I am creating a goal from my views, the association is not made, and the user_id of the goal user_id remain : nil.
Any ideas ?
EDIT AS REQUIRED :
_form.html.erb
<%= form_for(@goal) do |f| %>
<%= f.text_field :name, class: "form-control" %>
<%= f.text_area :description, class: "form-control" %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
goal_controller.rb
def new
@users = User.all
@goal = current_user.goals.build
end
def edit
end
def create
@goal = Goal.new(goal_params)
@goal.save
redirect_to root_path, notice: "Objectif sauvegardé"
end
Upvotes: 0
Views: 211
Reputation: 1602
def create
# Here!!!!
@goal = current_user.goals.new(goal_params)
@goal.save
redirect_to root_path, notice: "Objectif sauvegardé"
end
Upvotes: 1