2017-08-03 103 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場,你會得到一個不錯的表格填寫的所有信息。

相關問題