2012-01-17 47 views
2

我的Rails應用程序中有一個嵌套窗體/模型,除了before_save方法無法訪問父級用戶與嵌套形式,工作時的對象。它在我的ForumControler控制器保存子模型本身雖然..Ruby rails 3嵌套窗體無法保存,因爲before_save方法訪問的對象爲零的父模型

所以這裏時簡化代碼

class Forum < ActiveRecord::Base 
    has_many :forum_post, :dependent => :destroy 
    belongs_to :project 
    accepts_nested_attributes_for :forum_post, :reject_if => :all_blank 
end 

class ForumPost < ActiveRecord::Base 
    belongs_to :forum  
    belongs_to :user 
    before_save :toggle_forum    
    has_attached_file :attachment 

def toggle_forum 
    #a bunch of code 
    #one line tries to access @user.id but it fails because @user is nil 
    @user.id 


    end 

end 

然後工作正常,雖然這將更新這個我

def update 
@forum = Forum.find(params[:id])  
if @forum.update_attributes(params[:forum])    
    redirect_to(user_forum_path(@user,@forum.project,@forum), :notice => 'Forum was successfully updated.') 
    else   
    render :action => 'submit'   
    end 

在我看來:

<%= form_for(@forum, :url => user_forum_path, :html => { :multipart => true, :id => :project }) do |f| %>  
    <div class="form-label-row summary-text"> 
     <%= f.label(:summary_text, 'Final Summary') %> 
     <%= f.text_area :summary_text %> 
    </div> 

    <%= f.fields_for :forum_post,$forum_post do |child_form| %> 
     <div class="form-row-left attachment"> 
      <%= child_form.label :attachment %> 
      <%= child_form.file_field :attachment %>  
     </div> 
     <!-- I tried adding with and without the next 2 hidden fields and it failed either way --> 
     <%= child_form.hidden_field :user_id, :value=>@user.id %>    
     <%= child_form.hidden_field :forum_id, :value=>@forum.id %> 
    <% end %> 

    <%= hidden_field(:forum, :state, :value => :student_completed) %> 
    <div class="form-buttons" id="submit"> 
     <%= f.submit "Submit Project" %> 
    </div> 
<% end %> 

的問題是,如果@user爲零保存forum_post爲嵌套對象時..如果我救forum_post在自己的模式它的工作原理精細。任何想法爲什麼從父對象保存時@user變量沒有被填充?

+0

@user在哪裏創建的?它似乎來自你的更新行動的任何地方。 – bostonou 2012-01-17 04:41:33

回答

2

您確定要使用實例變量而不是關聯嗎?請嘗試:

def toggle_forum 
    #a bunch of code 
    #one line tries to access @user.id but it fails because @user is nil 
    user.id 
end 
+0

多數民衆贊成在這個問題..奇怪它與@ user.id時,通過直接用ForumPost創建一個對象設置..使我不知道什麼範圍是在Ruby中的類變量,因爲這些是在完全不同的類..也許它被設置在其他地方.. – 2012-01-17 04:41:08

+0

謝謝。當在before_create回調期間嘗試訪問self.parent以獲取子對象的派生值時,我遇到了類似的問題。直接訪問父項解決了我的範圍問題。 – Dan 2013-07-02 20:44:51

相關問題