开发者

Updating a model into another one in Rails

I have a model called Details that contains a method that updates some attributes with calculations by using another model's (Summary) attributes. I call that method into a before_saveto make Details' attributes update automatically when I modify an entry. I would like to make my Details' attributs update when I modify my entries in the Summary model. What I'm searching is something that could be used like that :

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

See the line : Details.updat开发者_运维问答e_all_attributes. All my Details' attributs would be saved and recalculated because of the before_save I have put. How can I do that ? Thanks.


Edit :

I just found the answer. I did a loop that saves all my entries.

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

Hope I will help some of you !


Fat models, skinny controllers:

Model

class Summary < ActiveRecord::Base
  after_update :recalculate_details

private

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

Controller

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜