How to add current_user to user_id to form_for in rails?
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
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