2016-08-15 297 views
0

我想獲得一個嵌套的屬性,形成檢測已經加載到數據庫中的值裝載值,任何人都可以看到什麼是錯這個代碼相關領域無法從數據庫

控制器

def edit 
    @merchant = Merchant.find(params[:id]) 
    @states = State.form_selector 
    @merchant.build_address if @merchant.address1.nil? 
    @merchant.build_account if @merchant.bsb.nil? 
    @products = Product.all 
    end 

查看

= form.fields_for :address do |address_fields| 
    = address_fields.hidden_field :address_type_id, value: 4 
    = address_fields.hidden_field :default, value: true 
    .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col 
     = address_fields.text_field :address1, class: 'mdl-textfield__input' 
     = address_fields.label :address1, class: 'mdl-textfield__label' 
    .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col 
     = address_fields.text_field :address2, class: 'mdl-textfield__input' 
     = address_fields.label :address2, class: 'mdl-textfield__label' 
    .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col 
     = address_fields.text_field :city, class: 'mdl-textfield__input' 
     = address_fields.label :city, class: 'mdl-textfield__label' 
    .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--2-col 
     = address_fields.text_field :zip_code, class: 'mdl-textfield__input', :pattern => '^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$' 
     = address_fields.label :zip_code, class: 'mdl-textfield__label' 
     %span.mdl-textfield__error= t('.postcode_error') 
    .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--3-col 
     = address_fields.select :state_id, @states, :include_blank => true 
     = address_fields.label :state_id, class: 'mdl-textfield__label' 
+0

你在你的Merchant模型中有'accep_nested_attributes_for:address'嗎? – coorasse

+0

是的數據被提交到數據庫,但是當你去編輯那個元素時,它從來沒有被保存過 –

+0

但是它叫做地址1還是地址?你猜他們混淆我猜:'@ merchant.build_address if @ merchant.address1.nil?' – coorasse

回答

0

@merchant.address返回一個集合,即使null返回一個數組。

@merchant.address # [] 
@merchant.address.nil? # false 
@merchant.address.blank? # true 

def edit 
    @merchant = Merchant.find(params[:id]) 
    @states = State.form_selecto 
    @merchant.build_address if @merchant.address.blank? 
    @merchant.build_account if @merchant.bsb.blank? 
    @products = Product.all 
end 

但我更喜歡在視圖中使用這種方式。因爲這樣你刪除了很多你的控制器操作代碼#edit #new #update #create

view 
- form.object.build_address if form.object.blank? 
= form.fields_for :address do |address_fields| 
    = address_fields.hidden_field :address_type_id, value: 4 
+0

使用.blank仍然讓我得到相同的結果 –

+0

顯示您的模型'merchant.rb' –

+0

你知道這寶石嗎? https://github.com/charliesome/better_errors –