首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails中不更新的form_for嵌套属性

rails中不更新的form_for嵌套属性
EN

Stack Overflow用户
提问于 2018-10-01 03:51:31
回答 1查看 32关注 0票数 0

我有一个表单,它应该更新一个嵌套属性(租户(用户)托管模型),我在获得正确的语法时遇到了问题。

_escrow_update_form.html.erb

<%= form_for @tenant,url: tenants_escrow_path,方法::修补程序,验证: true do \a颇具%> <%= a.fields_for :escrow do \f\x %> <%= f.label :new_amount_to_escrow %> <%= f.number_field(:escrow_payment) %> <% end %> <%= a.submit(“完成!返回到仪表板“,{class:"btn btn-成功btn-lg",:id=> 'goalButton'}) %> <% end %>

escrow_controller

def update @tenant = current_tenant if @tenant.escrows.update( escrow_params ) redirect_to tenants_dashboard_path,注意:“您的代管付款信息已更新”否则redirect_to tenants_escrow_path,通知:“您的托管付款未更新,请重试”结束私有def escrow_params params.permit(:escrow_payment,:home_value,:total_saved) end end

routes.rb

代码语言:javascript
复制
namespace :tenants do
  resources :escrow

代管模型

代码语言:javascript
复制
class Escrow
  include Mongoid::Document

  #associations
  belongs_to :tenant

租户模型

代码语言:javascript
复制
class Tenant
  include Mongoid::Document

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

  accepts_nested_attributes_for :escrow

模型不会更新。它给出了错误“NilClass的未定义方法‘`update’”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-01 05:04:04

“0:NilClass的未定义方法‘`update’”

这意味着@tenant没有任何escrow

_escrow_update_form.html.erb中,如果escrow为0,则构建@tenant.escrow

代码语言:javascript
复制
<% 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 %>

在强参数白名单嵌套参数中

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52584352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档