How to pass parameters using form_for to ruby ββon rails controller
I have a user model and a course model and the user can download courses for themselves after login.
However, I want the admin to be able to upload for users if the user is not versed enough.
My thought was to use the same upload action for both user upload and admin upload using an if statement.
The admin will select a user before he loads it on the users /: id page:
<%= link_to 'Upload Course for User', new_course_path(user_id: params[:id]), class: 'btn btn-primary' %>
Then I was able to see the create page with the parameter:
http: // localhost: 3000 / courses / new? user_id = 10
and i will submit this form
<%= form_for(@course, html: {class: "form-group"}) do |f| %>
...
<%= f.submit "Create Course", class: 'btn btn-primary' %>
for the create action in the controller:
def create
@course = Course.new(course_params)
@course.user_id = params[:user_id] || current_user.id
if @course.save
redirect_to course_path(@course), notice: 'The course has been created successfully!'
else
render 'new'
end
However, I never get the user_id parameters, always just current_user.id which is the admin_user id and that's not good.
How do I pass the user_id parameter to the controller to create the action so that it knows that I am trying to create for another user and not myself? Is there a better way to handle this than my logic?
Thank!
source to share
You can try this.
in the shape of.
<%= form_for(@course, html: {class: "form-group"}) do |f| %>
<%= hidden_field_tag "course[user_id]", "#{@user_id}" %>
<%= f.submit "Create Course", class: 'btn btn-primary' %>
In the way the controller is created.
def new
@user_id = params.has_key?("user_id") ? params[:user_id] | current_user.id
##OR
#@user_id = params[:user_id] || current_user.id
end
def create
@course = Course.new(course_params)
## OR
#@course.user_id = params[:user_id] || current_user.id
if @course.save
redirect_to course_path(@course), notice: 'The course has been created successfully!'
else
render 'new'
end
end
private
def course_params
params.require(:course).permit(:user_id)
end
source to share