2011-11-04 48 views
0

使用Rails 3.1.0的Rails 3.1的ActiveRecord怪異行爲創建行動

def create 
@practice = Practice.new(params[:practice]) 

respond_to do |format| 
    if (current_user.practices << @practice rescue false) 

    pmf = current_user.practices_users.inspect # if this line is removed the following update_attributes method breaks! 

    current_user.practices_users.last.update_attributes(:admin_flg => true, :first_name => params[:first_name], :last_name => params[:last_name]) 
    format.html { redirect_to home_dashboard_path, notice: 'Practice was successfully created.' } 
    format.json { render json: @practice, status: :created, location: @practice } 
    else 
    format.html { render action: "new" } 
    format.json { render json: @practice.errors, status: :unprocessable_entity } 
    end 
end 
end 

當 'PMF = ...' 行不存在,我得到這一行

NoMethodError: 
    undefined method `update_attributes' for nil:NilClass 

當'pmf = ...'行存在,創建操作正常工作。到底是怎麼回事?

+0

當你沒有'pmf ='行時'current_user.practices_users'的大小是多少?這可能是交易還沒有完成 –

+0

當你說「方法打破」,你是什麼意思?什麼是錯誤信息? – CharlieMezak

回答

2

我不知道確切的答案,但我可以幫你調試...

當你

pmf = current_user.practices_users.inspect 

然後滑軌從裝載整套practices_users(用於CURRENT_USER)數據庫,並且稍後您致電last時,它將調用Array類型的對象上的方法last

當你

current_user.practices_users.last 

,而不必做你的PMF的呼叫,整套practices_users尚未從數據庫加載到一個數組,和Rails是不會加載整個集,因爲所有你想要的是最後一個。當所有需要加載的項目都是最後一個項目時,加載項目數組將會很浪費。所以它會生成只從數據庫加載一行的SQL。

在這種情況下,您需要查看您的控制檯或開發日誌,以確切瞭解SQL Rails正在生成什麼以及SQL爲什麼沒有返回任何值。那麼它會變得清楚發生了什麼事情。

+0

謝謝。你讓我開始了,在我有時間充分追逐這個問題之前會有一點點。 – mikeborgh