0

I have a form and it is supposed to update a nested attribute (the tenant(user) escrow model) I am having trouble getting the correct syntax.

_escrow_update_form.html.erb

<%= form_for @tenant, url: tenants_escrow_path, method: :patch, validate: true do |a| %>   
 <%= a.fields_for :escrow do |f| %>   
  <%= f.label :new_amount_to_escrow %>
  <%= f.number_field(:escrow_payment) %>
 <% end %>
  <%= a.submit("Done! Go back to the Dashboard", {class: "btn btn-success btn-lg", :id=> 'goalButton'}) %>

<% end %>

escrow_controller

def update
 @tenant = current_tenant
 if @tenant.escrows.update(escrow_params)
    redirect_to tenants_dashboard_path, notice: "Your escrow payment informaton has been updated"
 else
    redirect_to tenants_escrow_path, notice: "Your escrow payment was not updated, try again"
 end  
private
  def escrow_params
    params.permit(:escrow_payment, :home_value, :total_saved)
  end 
end

routes.rb

namespace :tenants do
  resources :escrow

escrow model

class Escrow
  include Mongoid::Document

  #associations
  belongs_to :tenant

tenant model

class Tenant
  include Mongoid::Document

  has_one :escrow, autosave: true, dependent: :destroy

  accepts_nested_attributes_for :escrow

The model will not update. It gives the error "undefined method `update' for nil:NilClass"

1 Answer 1

1

"undefined method `update' for nil:NilClass"

Which means @tenant does't have any escrow

In _escrow_update_form.html.erb build a escrow if @tenant.escrow is nil

<% escrow = @tenant.escrow ?  @tenant.escrow : @tenant.build_escrow %>
<%= form_for @tenant, url: tenants_escrow_path, method: :patch, validate: true do |a| %>   
 <%= a.fields_for :escrow, escrow do |f| %>   
  <%= f.label :new_amount_to_escrow %>
  <%= f.number_field(:escrow_payment) %>
 <% end %>
  <%= a.submit("Done! Go back to the Dashboard", {class: "btn btn-success btn-lg", :id=> 'goalButton'}) %>

<% end %>

In strong parameter whitelist nested paramter

def update
 @tenant = current_tenant
 if @tenant.update(escrow_params) #updating @tenant will automatically update the corresponding escrow
    redirect_to tenants_dashboard_path, notice: "Your escrow payment informaton has been updated"
 else
    redirect_to tenants_escrow_path, notice: "Your escrow payment was not updated, try again"
 end
end
private
  def escrow_params
    params.require(:tenant).permit(:escrow_payment, :home_value, :total_saved, escrow_attributes: [])
  end 
end
Sign up to request clarification or add additional context in comments.

2 Comments

Question: Is building the model in the view sugar syntax?
@SupremeA You can also build it in controller side. with conditionally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.