Want to assign a user_id when a new object is created

I’m building a project organization app. Right now I have a User model and a Project model:

My User model:

class User < ActiveRecord::Base
  has_many :projects
end

Project model:

class Project < ActiveRecord::Base
  belongs_to :user
end

Once the user logs in they are redirected to their dashboard where there is a form to add a new project.

class DashboardsController < ApplicationController
  def show
    @project = Project.new
  end
end

dashboards/show

<h3>Add a new project:</h3>
<%= form_for @project do |form| %>
  <%= form.text_field :name, placeholder: 'Name your project!' %>
  <%= form.submit 'Create' %>
<% end %>

The project is persisting to the database but there isn’t a user_id associated with it. Here’s my create method:

class ProjectsController < ApplicationController
  def create
    @project = Project.create(project_parameters)

  if @project.save
	redirect_to dashboard_path
  else
	flash.alert = "Creation Aborted!"
	redirect_to dashboard_path
  end
end

def index
end

def show
end

private

def project_parameters
  params.require(:project).permit(:name)
end
end

What am I blowing up?

You’ll need to actually assign the current user as an attribute on project creation. Assuming you’re using some authentication gem which gives you ApplicationController#current_user, you can just put the following in #create:

@project = Project.new(project_parameters.merge(user: current_user)

if @project.save
   # ...

Thanks very much for your help. However, would you mind explaining what ‘merge’ does?

You could also merge from the project_params method to clean things up a little

def project_parameters
  params.
    require(:project).
    permit(:name).
    merge(user: current_user)
end

Another alternative would be to create the project from the association:

@project = current_user.projects.new(project_params)

When creating from an association it makes it less likely you’ll forget to merge it into the hash.

2 Likes
@project = current_user.projects.new(project_params)

This is what I was looking for! Thanks!