2017-03-23 20 views
0

我的Rails已經變得相當生疏,我開始瘋狂地試圖找出可能非常基本的東西,我看不到樹木的森林。在控制器中調用的Rails方法中類未定義的方法錯誤

我有一個表單,用於控制器的create操作。當我保存時,我還需要從另一個表中更新一些項目。我想把它全部包裝在一個交易中。我認爲首選是將交易放在模型中。當我這樣做,並嘗試打電話給create行動時,它錯誤地告訴我,該類沒有任何方法。

equip_swaps_controller.rb

def create 
    respond_to do |format| 
    @equip_swap = EquipSwap.new(equip_swap_params) 
    if @equip_swap.trans_equip_and_save 
     format.html { redirect_to @equip_swap, notice: 'Equipment transfer was successfully created.' } 
    else 
     format.html { render action: 'failure' } 
    end 
    end 
end 

型號equip_swap.rb

def self.trans_equip_and_save 
    EquipSwap.transaction do 
    Tool.transfer_equipment(self.to_vehicle, self.items_moved) 
    self.save 
    end 
end 

與所需的方法工具模型

def transfer_equipment(location,ids) 
    ids.each do |id| 
    Tool.find(id).update(location: location) 
    end 
end 

我認爲調用類的方法將允許它執行的是方法在我的實例EquipSwap實例@equip_swap。當我嘗試提交表單並創建新記錄時,它告訴我Class....沒有trans_equip_and_save方法。有些事情顯而易見,我錯過了。幫幫我!

回答

3

方法開始self它的呼叫類的方法,並和不self其呼叫實例的方法,讓我給例如

Class method 
def self.class_method 
    # do some stuff 
end 

Instance method 
def instance_method 
    # do some stuff 
en 

調用類的方法使用使用

ModelName.class_method 

Call實例方法

@instance_variable.instance_method 

在你的代碼中改變你我THOD以實例方法

def trans_equip_and_save 
EquipSwap.transaction do 
    Tool.transfer_equipment(self.to_vehicle, self.items_moved) 
    self.save 
end 
end 

現在調用此方法使用實例變量@equip_swap.trans_equip_and_save

編輯:

如果您使用的型號名稱叫transfer_equipment那麼之前的方法名稱添加self,我的意思是讓它類方法如下

def self.transfer_equipment(location,ids) 
    ids.each do |id| 
    Tool.find(id).update(location: location) 
    end 
end 
+0

我得到一個新的錯誤'未定義的方法'transfer_equipment」爲#<類別:0x007ff28ff9af18>'從線'Tool.transfer_equipment(self.to_vehicle,self.items_moved)'。我是否必須改變這些'self'來顯式調用實例? – Beartech

+0

更改爲'def self.transfer_equipment(location,ids)' – Sajin

+0

@Beartech檢查我編輯的答案 – ashvin

2

你有兩件事情在這裏看到,

首先,有兩種不同的方法,class methodsinstance methods

類方法:類方法直接定義在一個類上,它們使用def self.method定義。

用法:Class.method

實例方法:實例方法上的classobject定義,並且它們不具有自定義

用法:object = Class.new(), def method ==> object.method

所以,你的情況,將會有兩個變化,

1)你叫,@equip_swap.trans_equip_and_save

由於,@equip_swap是一個對象,根據你shold具有自第二點,@equip_swap是一個對象,根據你shold 具有無自一個實例方法的第二點。

def trans_equip_and_save 
    EquipSwap.transaction do 
    Tool.transfer_equipment(self.to_vehicle, self.items_moved) 
    self.save 
    end 
end 

2)Tool.transfer_equipment,這就是所謂的同class name。所以,根據第一點,應該自己調用

def self.transfer_equipment(location,ids) 
    ids.each do |id| 
    Tool.find(id).update(location: location) 
    end 
end 
+0

@Beartech,請檢查我的答案,您有2個更改。新增說明。 – Sravan

相關問題