如何使用form_for将参数传递给控制器​​ruby on rails [英] How to pass parameters with form_for to controller ruby on rails

查看:41
本文介绍了如何使用form_for将参数传递给控制器​​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.

我的想法是对用户上传和管理员上传使用相同的创建操作,并带有一个 if 语句.

My thought was to use the same create action for both user-upload and admin-upload, with an if statement.

管理员会在用户/:id查看页面为他上传之前选择用户:

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

我提交了这个表格

<%= 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

但是我从来没有得到 user_id 参数,总是只有 current_user.id,这是 admin_user 的 id,这不好.

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.

我如何设法将 user_id 参数传递给控制器​​创建操作,以便它知道我正在尝试为其他用户创建,而不是为我自己创建?有没有比我的逻辑更好的方法来处理这个问题?

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?

谢谢!

推荐答案

你可以试试这个.

在表格中.

<%= 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' %>

在控制器创建方法中.

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

这篇关于如何使用form_for将参数传递给控制器​​ruby on rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆