Ruby-on-rails 在模型中定义可以在控制器中访问的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3209817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
define method in model that can be accessed in controller
提问by Prateek
I have defined a problems method in my Report model. I need to use the value of Report.problem in the report's controller while defining the action show. But i keep getting the error message 'undefined method problem'. How do i solve this? Any assistance would be greatful.
我在我的 Report 模型中定义了一个问题方法。在定义动作表演时,我需要在报告的控制器中使用 Report.problem 的值。但我不断收到错误消息“未定义的方法问题”。我该如何解决这个问题?任何帮助都会很棒。
I have a report model and a problem model that contains a list of all problems.
我有一个报告模型和一个包含所有问题列表的问题模型。
In report model
在报表模型中
def problems1
Problem.find(:all, :conditions => )
end
In the reports controller i need something like
在报告控制器中,我需要类似的东西
def show
@report = Report.problems1
end
回答by Salil
you have to assign self.method_nameto use as a class method
您必须分配self.method_name以用作类方法
Follow following rule for Model methods
遵循模型方法的以下规则
Class Method
类方法
def self.problem
end
in controller
在控制器中
Report.problem
Instance method
实例方法
def problem
end
in controller
在控制器中
report = Report.new
report.problem
回答by Exorcist
If you define method as class method
如果将方法定义为类方法
class Report < ActiveRecord :: Base
def Report.problem
puts 1
end
end
Report.problem
>1
But if you define method as object
但是如果你将方法定义为对象
class Report < ActiveRecord :: Base
def problem
puts 1
end
end
This method call
这个方法调用
report = Report.new
report.problem
>1

