Ruby on rails 表单_,用于rails中未更新的嵌套属性
我有一个表单,它应该更新一个嵌套属性,即tenantuser托管模型。我在获取正确语法时遇到了问题 _托管更新表单.html.erb routes.rbRuby on rails 表单_,用于rails中未更新的嵌套属性,ruby-on-rails,Ruby On Rails,我有一个表单,它应该更新一个嵌套属性,即tenantuser托管模型。我在获取正确语法时遇到了问题 _托管更新表单.html.erb routes.rb namespace :tenants do resources :escrow 托管模式 class Escrow include Mongoid::Document #associations belongs_to :tenant 租户模型 class Tenant include Mongoid::Document
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
模型将不会更新。它给出了nil:NilClass的错误未定义方法“update”
nil:NilClass的未定义方法“update”
这意味着@tenant没有任何托管
如果@tenant.escrow为零,则在@escrow\u update\u form.html.erb中构建一个托管
问题:是否在视图中构建模型?SupremeA您也可以在控制器端构建它。有条件地。
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
<% 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