2011-09-08 3 views
1

컨트롤러 대신 모델에 논리를 넣고 싶습니다.레일에있는 컨트롤러에서 모델의 메서드에 액세스하는 방법

class UsersController < ApplicationController 
    def somemethod 
    d = User.methodinmodel 
    end 
end 

class User < ActiveRecord::Base 

    def methodinmodel 
    "retuns foo" 
    end 
end 

은 내가 User 모델에 대한 methodinmodel가 없다는 오류가 발생합니다.

왜? 오히려 특정 사용자보다 일반적으로 User 클래스에 methodinmodel를 호출 할 수있게하려면

답변

1

, 당신은 self를 사용하여 그것을 클래스 메소드를 만들 필요가 :

class User < ActiveRecord::Base 
    def self.methodinmodel 
    "returns foo" 
    end 
end 

현재 방법을 정의하고자에만 작업을 당신이 사용자에 호출하는 경우 : 허용 할 self을 사용하여 새 구현을 사용

@user = User.create! 
@user.methodinmodel # Works. 
User.methodinmodel # Doesn't work. 

당신은 그것을 좋아 호출 :

User.methodinmodel # Works. 
관련 문제