Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters with form_for to controller ruby on rails

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!

like image 318
Stephen Leung Avatar asked Jun 03 '15 09:06

Stephen Leung


2 Answers

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
like image 130
Amit Sharma Avatar answered Oct 19 '22 19:10

Amit Sharma


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

So it will be passed as form element

like image 20
Vrushali Pawar Avatar answered Oct 19 '22 18:10

Vrushali Pawar