嵌套属性不会在设计视图中显示Rails 4

时间:2016-07-11 10:17:53

标签: ruby-on-rails ruby devise nested-forms cocoon-gem

我有一个应用程序,其用户模型可以包含许多地址。我希望能够在用户通过嵌套属性注册时为用户添加地址。我也在使用设计用户模型。

型号:

class Address < ActiveRecord::Base
belongs_to :user

end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

has_many :addresses

accepts_nested_attributes_for :addresses

end

注册管理员:

class Users::RegistrationsController < Devise::RegistrationsController
before_action :set_user, only: [:show]


def new
  resource = build_resource({})  
  resource.addresses.build
  respond_with_navigational(resource){ render_with_scope :new } 
 end

 def create
   super
 end



private 

def set_user
@user = User.find(params[id])

end

def user_params
params.require(:user).permit(:email, :password, :first_name,                  
:last_name, :phonenumber, :addresses_attributes => [:postcode,  
:housenumber, :streetname, :city, :town] )

   end
 end

注册视图中表单的字段:

   <%= f.simple_fields_for :addresses do |address|%>
  <%= address.input :housenumber %>
  <%= address.input :postcode %>
  <%= address.input :streetname%>
  <%= address.input :town%>
  <%= address.input :city%>
    <%end%>

2 个答案:

答案 0 :(得分:0)

您需要将以下方法添加到ApplicationController:

class ApplicationController < ActionController::Base
  # Your code

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_in) do |user_params|
      user_params.permit(:email, :addresses_attributes => [:postcode, :housenumber, :streetname, :city, :town])
    end
  end
end

这允许您允许设计模型的嵌套属性。查看repo页面并搜索“嵌套”#39;了解更多信息:

https://github.com/plataformatec/devise

答案 1 :(得分:0)

我知道这有点旧,但这可能会在将来拯救某人。 实施configure_sign_up_params后,您必须在动作创建中使用它,以便Users::RegistrationsController看起来像这样:

class Users::RegistrationsController < Devise::RegistrationsController
    before_action :set_user, only: [:show]
    before_action :configure_sign_up_params, only: [:create]

    # more code bellow...
    protected

      def configure_sign_up_params
          devise_parameter_sanitizer.permit(
              :sign_up,
              keys: [:email, :password, :password_confirmation,
              # put any other keys in here                 
          ])
      end
end