如何使用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