2011-08-29 116 views
2

我試圖讓我的頭保存到一個控制器的多個模型,它可能很簡單,但我無法弄清楚。Ruby on Rails - 從一個控制器更新多個模型

我有一個用戶模型,有很多loanitemsloanitems屬於用戶關聯設置。

在我loanitems控制器我希望每個loanitem創建行動,以更新的user.points

所以此刻我有下面的代碼不拋出任何錯誤,但不更新該用戶模型。

def create 
    @loanitem = current_user.loanitems.build(params[:loanitem]) 
    respond_to do |format| 
     if @loanitem.save 
     @loanitem.user.points = @loanitem.user.points + 50 
     @loanitem.user.save 
     format.html {redirect_to root_path, :flash => {:success => "Loan Item created" } } 
     format.xml{render xml: root_path} 
     else 
     format.html {render 'pages/home' } 
     format.xml {render xml: 'pages/home'} 
     end 
    end 
    end 

我也想上一個主題

def create 
    @loanitem = current_user.loanitems.build(params[:loanitem]) 
    respond_to do |format| 
     if @loanitem.save 
     current_user.points = current_user.points + 50 
     current_user.save 
     format.html {redirect_to root_path, :flash => {:success => "Loan Item created" } } 
     format.xml{render xml: root_path} 
     else 
     format.html {render 'pages/home' } 
     format.xml {render xml: 'pages/home'} 
     end 
    end 
    end 

以下變化,但我應該不是發送一些消息給userupdate控制器呢?目前看起來像這樣...

def update 
    @user = User.find(params[:id]) 
    if 
    @user.update_attributes(params[:user]) 
    redirect_to @user, :flash => { :success => "Profile has been updated!"} 
    else 
    @title = "Edit Profile" 
    render 'edit' 
    end 
end 

或者我聽說,真的都應該包含在模型中,所以也許方法應該寫在User.rb然後叫由Loanitems控制器業務邏輯創建方法?

我知道這是一個真正的新秀問題,但任何建議都會非常受歡迎。

回答

1

這聽起來像你需要使用一個交易,這樣你就可以修改多個項目作爲單個原子單位:

def create 
    respond_to do |format| 
     User.transaction do 
     begin 
      @loanitem = current_user.loanitems.create!(params[:loanitem]) # raises exception if it can't create 
      @loanitem.user.update_attributes!(:points => @loanitem.user.points + 50) # raises exception if it can't update 

      format.html {redirect_to root_path, :flash => {:success => "Loan Item created" } } 
      format.xml{render xml: root_path} 

     rescue ActiveRecord::RecordInvalid 
      format.html {render 'pages/home' } 
      format.xml {render xml: 'pages/home'} 

      raise ActiveRecord::Rollback 
     end 
     end 
    end 
    end 

這可以讓你有一個簡單快樂的路徑,其中多個對象進行更新/創建如果出現任何錯誤並且呈現錯誤處理邏輯,則回滾所有更改。對象將具有可以顯示給用戶的驗證消息。

+0

我之前沒有遇到過這個交易 - 雖然看起來不錯 - 會給它一個旋風,然後回到你身邊。歡呼的幫助! –

+0

嘿溫菲爾德 - 給了這個鏡頭 - 但它失敗@ loanitem.user.update_attributes!(:points => @ loanitem.user.points + 50)線。我試着在用戶模型中指出attr_accessor,但是拋出你沒有期望的時候有一個無對象! 您可能預期了Array的一個實例。 評價爲零時發生錯誤+(我真的只是猜測那裏) –

+0

Winfield我得到它的工作 - 感謝您的幫助 - 我做了一個小小的改變,因爲我對用戶模型的電子郵件和密碼進行了驗證 - 我需要將這些值傳遞給update_attributes方法 - 再次感謝您的幫助。 –

相關問題