← Back to Upcase

Want to assign a user_id when a new object is created


(Jameson Trinker) #1

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?


(pat brisbin) #2

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
   # ...

(Jameson Trinker) #3

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


(Harlow Ward) #4

http://www.ruby-doc.org/core-2.0/Hash.html#method-i-merge

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.


(Jameson Trinker) #5
@project = current_user.projects.new(project_params)

This is what I was looking for! Thanks!