使用nested_attributes进行设计——显示数据但不更新模型的字段



我有以下代码(Slim格式),它显示了users的表单。user的数据在提交时显示并更新。但是,phonepublisher的嵌套属性,它在我加载表单时显示当前数据,但在提交时不会更新。

查看

= form_for current_user, url: user_registration_path, html: {class: 'account'} do |user_form|
  .row
    .control-group.text-center
      label.col-9 Email
      = user_form.text_field :email, class: 'col-7'
  = fields_for :publisher, current_user.publisher do |publisher_form|
    .row
      .control-group.text-center
        label.col-9 Phone
        = publisher_form.text_field :phone, class: 'col-7'

注册控制器

class RegistrationsController < Devise::RegistrationsController
  def update_resource(resource, params)
    resource.update_without_password(params)
  end
end

应用程序控制器

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?
  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) {|u| u.permit(
        :first_name,
        :last_name,
        :email,
        :password,
        :password_confirmation,
        :current_password,
        publisher_attributes: [:phone, :payment_details],
        banner_attributes: [:website, :banner_msg, :signup_msg, :bg_col, :txt_col, :btn_col]
      )}
  end
end

用户模型

class User < ActiveRecord::Base
  has_one :publisher
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  accepts_nested_attributes_for :publisher
  validates_presence_of :first_name, :last_name
  validates_length_of :first_name, maximum: 100
  validates_length_of :last_name, maximum: 100
end

我终于发现

= fields_for :publisher, current_user.publisher do |publisher_form|

应该是:

= user_form.fields_for :publisher, current_user.publisher do |publisher_form|

最新更新