【问题标题】:Updating a model into another one in Rails在 Rails 中将模型更新为另一个模型
【发布时间】:2011-07-27 13:09:25
【问题描述】:

我有一个名为 Details 的模型,其中包含一个方法,该方法通过使用另一个模型的 (Summary) 属性来更新某些属性的计算。我将该方法称为before_save,以便在我修改条目时自动更新Details' 属性。当我修改 Summary 模型中的条目时,我想更新我的 Details' 属性。我正在搜索的是可以这样使用的东西:

def update
    @summary = Summary.find(params[:id])
    if @summary.update_attributes(params[:summary])
      (Details.update_all_attributes)
      flash[:notice] = "Updated!"
      redirect_to edit_summary_path(@summary)
    else    
      render :action => 'edit'
    end
  end

见线路:Details.update_all_attributes。由于我放了before_save,我所有的Details' 属性都将被保存并重新计算。我怎样才能做到这一点 ?谢谢。


编辑:

我刚刚找到了答案。我做了一个循环来保存我的所有条目。

def update
    @summary = Summary.find(params[:id])
    if @summary.update_attributes(params[:summary])
       @details = Details.all
       @details.each do |detail|
        detail.save!
       end
       flash[:notice] = "Updated!"
       redirect_to edit_summary_path(@summary)
    else    
       render :action => 'edit'
    end
  end

希望我能帮助你们中的一些人!

【问题讨论】:

  • 这两个模型是否以某种方式相关,还是您尝试调用的类方法?
  • 我刚刚找到了我正在搜索的内容。我将在 8 小时内发布我的答案,因为我现在做不到。

标签: ruby-on-rails model save


【解决方案1】:

胖模型,瘦控制器:

型号

class Summary < ActiveRecord::Base
  after_update :recalculate_details

private

  def recalculate_details
   Detail.all.each {|d| d.save! }
  end
end

控制器

def update
    @summary = Summary.find(params[:id])
    if @summary.update_attributes(params[:summary])
       flash[:notice] = "Updated!"
       redirect_to edit_summary_path(@summary)
    else    
       render :action => 'edit'
    end
  end

【讨论】:

  • 感谢您的提示!我会这样做的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多