2016-07-17 62 views
-1

我的標準守則Rails的5 +嵌套屬性具有errror上HAS_ONE創建

class Bank < ApplicationRecord 
    has_one :address 
    accepts_nested_attributes_for :address 
end 



class Address < ApplicationRecord 
    belongs_to :bank 
end 

我的控制器

def create 
    @bank = Bank.new(bank_params) 

    respond_to do |format| 
     if @bank.save 
     format.html { redirect_to @bank, notice: 'Bank was successfully created.' } 
     format.json { render :show, status: :created, location: @bank } 
     else 
     format.html { render :new } 
     format.json { render json: @bank.errors, status: :unprocessable_entity } 
     end 
    end 
end 

def bank_params 
     params.require(:bank).permit(:code, :currency, :name, :mobile_1, :mobile_2, :email, address_attributes: [:id, :name, :area, :pin_code, :city_id]) 
end 

它給錯誤類似的東西

@信息= {」 address.bank「=> [」must exist「]},@details = {」address.bank「=> [{:error =>:blank}

爲什麼它顯示反向...不理解

+0

地址模型是什麼樣的。在我看來,你有評估銀行的評估驗證,看起來像是失敗了。因此,你看到它在反向 – Doon

回答

5

我敢肯定這是因爲您的銀行地址模型有一個驗證。然而,基於觀察,我認爲Rails的嘗試:

validate your parent model 
validate your child model # validation fails here because parent doesn't have an id yet, because it hasn't been saved 
save parent model 
save child model 

不過,我認爲你應該能夠通過使用:inverse_of選項像這樣來解決這個問題:

class Bank < ApplicationRecord 
    has_one :address, inverse_of: :bank 
    accepts_nested_attributes_for :address 
end 

class Address < ApplicationRecord 
    belongs_to :bank, inverse_of: :address 
    validates :bank, presence: true 
end 

讓我知道這是否爲你的作品

+0

你好先生......它解決了我的問題......但我仍然不理解......爲什麼inverse_of要求? 願你幫助我解決這個疑問嗎?這將是很大的幫助。 – Mukesh

+1

':inverse_of'選項主要用於優化。它基本上是說引用關聯的內存對象。這是需要的,因爲在驗證您的子模型時,關聯的對象尚未保存,並且關聯對象默認情況下不會引用內存中的對象。 – oreoluwa

+0

這裏有一篇文章可以更好地解釋這個問題:https://www.viget.com/articles/exploring-the-inverse-of-option-on-rails-model-associations – oreoluwa

2

導軌5使得belongs_to的默認需要協會

By using (optional: true), we can change behavior 

class Bank < ApplicationRecord 
    has_one :address, optional: true 
    accepts_nested_attributes_for :address 
end 



class Address < ApplicationRecord 
    belongs_to :bank, optional: true 
end