вложенный атрибут form_for не обновляется в рельсах - PullRequest
0 голосов
/ 01 октября 2018

У меня есть форма, и она должна обновить вложенный атрибут (модель условного депонирования арендатора (пользователя)). У меня проблемы с получением правильного синтаксиса.

_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

rout.rb

namespace :tenants do
  resources :escrow

модель условного депонирования

class Escrow
  include Mongoid::Document

  #associations
  belongs_to :tenant

арендатормодель

class Tenant
  include Mongoid::Document

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

  accepts_nested_attributes_for :escrow

Модель не будет обновляться.Выдает ошибку "неопределенный метод` update 'для nil: NilClass "

1 Ответ

0 голосов
/ 01 октября 2018

"неопределенный метод` update 'для nil: NilClass "

Это означает, что @tenant не имеет escrow

в _escrow_update_form.html.erb сборкеa escrow, если @tenant.escrow равно 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 %>

В параметрах со вложенными параметрами в белом списке с сильными параметрами

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...