我在rails 4应用程序中使用devise进行用户身份验证。
用户注册后,我将用户重定向到一个页面,该页面包含一些可以选择填充的其他字段。我的表单显示正确,但它没有将嵌套属性保存到数据库。
我有一个名为" seeker_skill"与用户有这种关系:
用户has_many seeker_skills seeker_skills属于用户
user.rb
class User < ActiveRecord::Base
has_many :seeker_skills, dependent: :destroy
accepts_nested_attributes_for :seeker_skills, :reject_if => lambda { |a| a[:skill].blank? }, :allow_destroy => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
users_controller.rb
class UsersController< ApplicationController
def job_seeker_additional_fields
@user = current_user
@user.seeker_skills.build
@seeker_skill = current_user.seeker_skills.build
end
end
seeker_skill.rb
class SeekerSkill < ActiveRecord::Base
belongs_to :user
validates :skill, presence: true
end
seeker_skills_controller.rb
class SeekerSkillsController < ApplicationController
def create
@seeker_skill = current_user.seeker_skills.build(seeker_skill_params)
if @seeker_skill.save
redirect_to root_url
else
flash[:error] = "Invalid Input"
redirect_to myskills_path
end
end
def destroy
end
def new
@seeker_skill = current_user.seeker_skills.build
@user = current_user
end
private
def seeker_skill_params
params.require(:seeker_skill).permit(:skill)
end
end
我相信我在应用程序控制器中正确设置了允许的参数。 的 application_controller.rb
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :role, :email,
:company, :password, :password_confirmation, :remember_me,
seeker_skills_attributes: [:id, :skill, :user_id, :_destroy]) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login,
:username, :role, :email, :company, :password, :remember_me) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :bio,
:min_salary, :location, :radius, :role, :email, :company, :password, :password_confirmation,
:current_password, seeker_skills_attributes: [:id, :skill, :user_id, :_destroy]) }
end
end
最后,视图中有表格:最后我会添加选项,一次添加多项技能。
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= f.fields_for(@seeker_skill) do |f| %>
<%= f.text_field :skill, placeholder: "Add skill" %>
<% end %>
<%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>
我错过了什么?我已经使用自定义用户身份验证系统进行了设置,但从未使用过设计。
答案 0 :(得分:0)
将嵌套字段调用更改为:
<%= f.fields_for(:seeker_skill) do |f| %>
带符号,而不是对象。当使用object创建时,它会从对象类名称中命名该字段,因此在结果中您获得了params[:user][:seeker_skill]
,然后由强参数进行过滤。在使用符号运行时,它会尝试使用给定名称执行方法,将其视为对象,如果表单对象定义<name>_attributes
,则将子对象名称设置为<name>_attributes
。