Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add current_user to user_id to form_for in rails?

I have a form for creating materials (title, description and content - all basic). The form saves these details just fine but it doesn't save the user_id, which should be the user_id of the current_user. How do I do this? It must be easy but nothing has worked so far.

def create 
   @material = Material.new(params[:material])
   if @material.save
     flash[:success] = "Content Successfully Created"
     redirect_to @material
   else
     render 'new'
   end
end
like image 685
Finnjon Avatar asked Oct 06 '12 12:10

Finnjon


2 Answers

def create 
 @material = Material.new(params[:material])
 @material.user_id = current_user.id if current_user
 if @material.save
  flash[:success] = "Content Successfully Created"
  redirect_to @material
 else
  render 'new'
 end
end
like image 102
Arpit Vaishnav Avatar answered Nov 10 '22 22:11

Arpit Vaishnav


There are a few different ways to do it depending on how you have your application setup. If there is a relationship between the user and materials (User has many materials), you could use that in your controller:

def create
  @material = current_user.materials.new(params[:material])
  # ...
end

If you don't have that relationship, I would still recommend setting it in the controller as opposed to a hidden field in the form. This will be more secure because it won't let someone tamper with the user id value:

def create
  @material = Material.new(params[:material].merge(user_id: current_user))
  # ...
end
like image 5
Peter Brown Avatar answered Nov 10 '22 22:11

Peter Brown