【问题标题】:Can't use updated model with association in the same view无法在同一视图中使用具有关联的更新模型
【发布时间】:2014-05-19 09:28:19
【问题描述】:

我有一个@parent 模型,其中有很多@kids 模型

@parent = Parent.find(par_id)
@kid = @parent.kids.first

@parent.update_attributes(params) #change parent's name

@kid.parent@parent 不同,尽管 @kid.parent == @parent 唯一的区别是 Parent.name 不同

这会导致孩子的视图使用旧的父名称呈现错误 在视图中:

<%= @kid.parent.name %> #=> this renders the old name and not the newly updated on

有没有办法刷新关联或模型?

【问题讨论】:

    标签: ruby-on-rails caching ruby-on-rails-4 model model-associations


    【解决方案1】:

    您可以使用ActiveRecord's reload 方法。

    @kid.parent.reload # or just @kid.reload
    @kid.parent.name # the new name, freshly fetched from the DB
    

    【讨论】:

      【解决方案2】:

      为什么在更新@parent 之后不搜索@kid?喜欢

      @parent = Parent.find(par_id)
      @parent.update_attributes(params) #change parent's name
      @kid = @parent.kids.first
      

      让我们先为该特定对象完成一项工作,并在完成一项工作后使用它。

      在您的情况下,分配是主要问题。一旦分配了@kid 对象,它将与正在更新的对象分开

      【讨论】:

        猜你喜欢
        • 2021-05-25
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多