I have a user model and a course model, and user can upload courses for themselves after they login.
However, I want admin to be able to upload for users to in case the user is not savvy enough.
My thought was to use the same create action for both user-upload and admin-upload, with an if statement.
The admin will select the user before he uploads for him in users/:id view 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 submit this form
<%= form_for(@course, html: {class: "form-group"}) do |f| %>
...
<%= f.submit "Create Course", class: 'btn btn-primary' %>
to 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'm never getting the user_id params, always just the current_user.id, which is the admin_user's id and that's not good.
How do I manage to pass in the user_id parameter to the controller create action so that it knows I'm trying to create for another user, not myself? Is there a better way to handle this than my logic?
Thanks!
You can try this.
in Form.
<%= 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 controller create method.
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
<%= f.hidden_field :user_id, :value => params[:user_id] %>
So it will be passed as form element
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