Use this (if you already have current_user method available):
<%= f.hidden_field :user_id, :value => current_user.id %>
If you don't have current_user method implemented, in your corresponding controller, you can have something like this:
@current_user = User.find(params[:user_id])
Then, in your view, you can do:
<%= f.hidden_field :user_id, :value => @current_user.id %>
Update
After the above conversation, if you want to use session to store the user_id, then you can do something like this.
You can create a SessionsHelper module (which you can include in your ApplicationController) where you can define a log_in method:
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
(You can also put this: session[:user_id] = user.id in the create action where you create an user.)
You can also define a current_user method in this module:
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
Here are some other useful helper methods that you can add in this module:
# Returns true if the given user is the current user.
def current_user?(user)
user == current_user
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
@current_user = nil
end
Finally, I would suggest you to take a look at Devise gem which is a very popular authentication solution for Rails application.
params[:user_id]can be modified manually. You probably have a session between your app and the end-user, in this session is stored the User's id (usually, depending on your user-sessions solution). Use this to set theuser_idof the object beeing created/updated. Something likeItem.create(params[:item].merge(user_id: current_user.id))@current_user = User.find(session["user_id]")