2012-08-08 72 views
0

我有一個複選框,如果選中,允許創建我的孩子資源稱爲工程師。我試圖通過我的模型創建它,因爲這是我可以調用after_save方法的地方。未從父模型創建子項?

這裏是我的代碼:

型號/ user.rb

class User < ActiveRecord::Base 
    has_many :armies 
    has_many :engineers 
end 

型號/ army.rb

class Army < ActiveRecord::Base 
has_many :engineers 
attr_reader :siege 
after_save :if_siege 
private 

def if_siege 
    if self.siege 
    Engineer.create!(:user_id => current_user.id, :army_id => self.id) 
    end 
end 
end 

型號/ engineer.rb

class Engineer < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :army 
end 

控制器/ armies_controller.rb

def new 
    @army = Army.new 
end 

def create 
    @army = current_user.armies.build(params[:army]) 
    if @army.save 
     redirect_to new_army_path 
    else 
     render :new 
    end 
    end 
end 

雖然我if_siege方法這給了我一個錯誤:

undefined local variable or method `current_user' 

我怎樣才能解決這個問題或有另一種方式來做到這一點?不知道這是否應該在控制器或模型中進行,但我只能把這些放在模型中。

謝謝。

+0

@jordanpg它的設計方法。 – LearningRoR 2012-08-09 01:05:41

回答

1

添加belongs_to :userArmy模型

Army#if_siege,更新Engineer.create!如下

Engineer.create!(:user_id => self.user.id, :army_id => self.id) 
1

首先,CURRENT_USER對象將不會在模型層的背景下存在的,除非你的身份驗證是做什麼使其可用。儘管這通常是非線程安全的方法。也許對你來說這不是問題。

Current User Instantiation

話雖如此,一種方法(也許不是理想的方式)來解決,這是通過創建名爲陸軍的對象模型中的attr_accessor。然後將current_user設置爲在current_user實例可用的控制器中的Army 新的操作中。

# in the Army model 
attr_accessor :the_user 

# in the Army Controller 
@army = Army.new(:the_user => current_user.id) 

您還必須通過對創建操作添加一個隱藏字段存儲在你看來這個值來進行此操作。

只是一個觀察,但我很確定在「if_seige」方法中自我調用是多餘的。 self應該已經在該方法中的軍隊對象範圍內。