5

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!

2
  • 2
    You can use a hidden_field to pass on the user_id to create action Commented Jun 3, 2015 at 9:29
  • @Stephen Leung, please post your controller new method and course_params method Commented Jun 3, 2015 at 9:59

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

4
<%= f.hidden_field :user_id, :value => params[:user_id] %>

So it will be passed as form element

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.