Mukesh Mukesh - 4 months ago 46
Ruby Question

Rails 5 + Nested Attribute with has_one having errror on create

My Model Code

class Bank < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end



class Address < ApplicationRecord
belongs_to :bank
end


My Controller

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


It's giving error something like that

@messages={:"address.bank"=>["must exist"]}, @details={"address.bank"=>[{:error=>:blank}

why it's showing reverse... not understanding

Answer

Rails 5 makes belongs_to association required by default

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