我有Devise user
模型和关联的profile
模型。这是:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile, autosave: true
accepts_nested_attributes_for :profile
before_create :build_profile
end
个人资料模型:
class Profile < ActiveRecord::Base
belongs_to :user
end
接下来,我在默认设计视图中包含配置文件字段:
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %>
</div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
<% end %>
<%= f.fields_for :profile do |profile_form| %>
<div class="field">
<%= profile_form.label :username %><br />
<%= profile_form.text_field :username %>
</div>
<div class="field">
<%= profile_form.label :address %><br />
<%= profile_form.text_field :address %>
</div>
<div class="field">
<%= profile_form.label :pin %><br />
<%= profile_form.text_field :pin %>
</div>
<% end %>
<div class="field">
<%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
<h3>Cancel my account</h3>
<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>
<%= link_to "Back", :back %>
现在,当我更新表单时,更新了Devise字段,但是更新了配置文件字段。如果我尝试通过rails控制台更新配置文件,一切都很好。
u = User.find_by(id: 2)
u.profile.pin = 123
u.save
答案 0 :(得分:0)
解决!只需在ApplicationController中覆盖Devise allowed_parameters,如下所示:
before_action :configure_devise_permitted_parameters, if: :devise_controller?
protected
def configure_devise_permitted_parameters
registration_params = [:email, :password, :password_confirmation, profile_attributes: [:username, :address, :pin]]
if params[:action] == 'update'
devise_parameter_sanitizer.for(:account_update) {
|u| u.permit(registration_params << :current_password)
}
elsif params[:action] == 'create'
devise_parameter_sanitizer.for(:sign_up) {
|u| u.permit(registration_params)
}
end
end
感谢@max的回答。