我正在尝试为用户编写将技能(属于用户,技术和水平)添加到其技能组的功能的代码。
我在skill / new.html.erb中有一个simple_for_for:
<%= simple_form_for [ @user, @skill ] do |f| %>
<p>Select Tech</p>
<div>
<%= f.collection_select :technology_id, @techs, :id, :name%>
</div>
<p>Select Level</p>
<div>
<%= f.collection_select :level_id, @levels, :id, :name%>
</div>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
Skills Controller:技能操作:将Technology和Level对象的列表传递给simple_form_for,因此用户可以选择的选项是所有Technologies和Levels的列表(例如Tech:Ruby,Level:Junior)。
class SkillsController < ApplicationController
before_action :authenticate_user!
def index
@skills = policy_scope(Skill)
end
def new
@techs = Technology.all
@levels = Level.all
@skill = Skill.new
@user = current_user
authorize @skill
end
def create
skill = Skill.new(skill_params)
authorize skill
if skill.save
redirect_to projects_path
else
render :action => "new", @user => params[:user_id], @skill => skill
end
end
private
def skill_params
params.require(:skill).permit(:user_id, :technology_id, :level_id)
end
end
我有几个问题:
在无法保存新技能后,else子句不会将@user和@skill正确发送到表单,但是我不知道语法是否正确。
实际问题:可以将与所选选项相关联的技术和级别ID而不是对象本身传递给表单吗?我尝试手动手动查找所有技能组件,如下所示,这会导致“找不到没有ID的用户”错误:
def create
skill = Skill.new()
technology = Technology.find(skill_params[:technology_id])
level = Level.find(skill_params[:level_id])
user = User.find(skill_params[:user_id])
skill.user = user
skill.technology = technology
skill.level = level
authorize skill
if skill.save
redirect_to projects_path
else
render :action => "new", @user => user, @skill => skill
end
end
private
def skill_params
params.require(:skill).permit(:technology_id, :level_id, :user_id)
end
首先,请确保您已建立从用户到技能的关联,可以根据以下条件建立新的记录:
class User
has_many :skills
end
如果您的应用程序仅允许用户向自己的帐户添加技能,则应从会话中获取当前用户:
def create
@skill = current_user.skills.new(skill_params)
authorize @skill
if @skill.save
redirect_to projects_path
else
render :new
end
end
请注意,这消除了完全嵌套表单和路由的需要:
resources :skills
<%= simple_form_for @skill do |f| %>
# ...
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句