2017-08-03 107 views
0

我正在尝试创建一个表单,为具有一个billing_information的模型用户创建新记录。 Billing_information有一个属性account_name,我想包含在表单中。我尝试使用委托方法,但它不工作。它产生: -rails_admin如何在创建表单中包含子属性

error: unknown attribute 'billing_information_account_name' for User.

class User < ActiveRecord::Base 
    accepts_nested_attributes_for :billing_information 
    has_one :billing_information, inverse_of: :user 
    delegate :account_name, to: :billing_information, allow_nil: true 

    rails_admin do 
     create do 
     field :name 
     field :email 
     field :billing_information_account_name do 
      def value 
       bindings[:object].account_name  
      end 
     end 
     end 
    end 
end 

有没有人有一个更好的解决方案?谢谢。

回答

0

不幸的是,在这种情况下,您将无法从rails管理员那里获得帮助,但我可以做到。

您必须添加一个新的虚拟字段并在setter中处理输入。看看这个例子。

class User < ApplicationRecord 
    has_one :billing_information, inverse_of: :user 

    # A getter used to populate the field value on rails admin 
    def billing_information_account_name 
     billing_information.account_name 
    end 

    # A setter that will be called with whatever the user wrote in your field 
    def billing_information_account_name=(name) 
     billing_information.update(account_name: name) 
    end 

    rails_admin do 
     configure :billing_information_account_name, :text do 
     virtual? 
     end 

     edit do 
     field :billing_information_account_name 
     end 
    end 
    end 

您可以随时创建使用嵌套属性战略全面billing_information,这意味着加billing_information场,你会得到一个不错的表格填写的所有信息。

相关问题