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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With