[英]Error call method of model from other Controller Rails 4 undefined method
使用Rails 4.0
我認為這是一個小問題,我創建了一個Word.rb模型,並且該模型具有創建新Word的方法,我的問題是當我嘗試使用Word.saveWord(params..)
訪問此方法時,此方法返回的是未定義的方法,我展示了最好的文件說明:
Word.rb
class Word < ActiveRecord::Base
def saveWord(*args)
args.each do |term|
@term = Word.new(:name => term,:score => 0)
@term.save
end
end
before_save :check_repeated
def check_repeated
@term = Word.find_by_name(self.name)
@term.score += 1 if @term.present?
end
我不知道是否可以從其他控制器使用此方法,因為我嘗試從我的recipes_controller.rb使用 :
def search
@recipes = Recipe.search(params[:term],params[:term_1],params[:term_2]) if request.get?
respond_to do |format|
format.json { render :json => @recipes,:only => [:id,:name,:rcp_img_file_name,:time] }
format.xml { render :xml => @recipes }
# render :xml => @recipes.to_xml(:include => :category)
#render :xml => @recipes
end
Word.saveWord(params[:term].to_s)
end
我給這個錯誤:
undefined method `saveWord' for #<Class:0x007feb3f09bac8>
..
Word.saveWord(params[:term].to_s)
end
請有人對我提出建議嗎? 非常感謝。
您將saveWord
實現為實例方法,但嘗試將其稱為類方法。 您可能需要將其重新實現為類方法:
def self.save_word(*args)
args.each do |term|
@term = Word.new(:name => term,:score => 0)
@term.save
end
end
我還更改了此方法的名稱,因此現在它遵循Ruby命名約定。
您的saveWord
是一個實例方法,但您將其稱為class
方法。 由於您要在saveWord
方法中實例化一個新Word
,因此我假設您想將其保留為類方法。 在這種情況下,將saveWord
方法更新為實例方法如下:
class Word < ActiveRecord::Base
def self.saveWord(*args)
args.each do |term|
@term = Word.new(:name => term,:score => 0)
@term.save
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.