我对Rails很陌生,而我正在从事的项目要求我访问现有方法。但是,它是用模型编写的,我不确定如何才能使其在我的API需要命中的控制器中运行
我尝试路由到模型中的方法,但得知我做不到。从我收集到的信息来看,这就是它的工作方式,对吧?
model.rb
def method_i_need
//code
end
controller.rb
def method_to_call_other_method
//code
end
答案 0 :(得分:1)
冒着偷@sergio的积分的危险...
如果您的方法是在Model.rb中定义的,则以下两项将在您的控制器中起作用:
def method_to_call_other_method
Model.first.method_i_need
end
def method_to_call_other_method
Model.find(params[:id]).method_i_need
end
正如评论员所说,您只需要模型实例(Model.first或Model.find(params [:id])),然后在模型实例上调用您在模型中定义的方法。而且params [:id]显然取决于您要通过的参数。
答案 1 :(得分:1)
任何类实例都将具有可在实例对象上调用的公共实例方法。在控制器动作中实例化模型类实例是很常见的。 这是一个详细说明以前的答案的示例,并说明了如何在Rails中实现此目的。
class Person < ActiveRecord::Base
def say_hello
language == 'DE' ? 'Guten Tag' : 'Hello'
end
end
class PersonsController < ApplicationController
def random_person
@random_person = Person.find(Person.pluck(:id).sample)
# you can now call @random_person.say_hello
end
def person_greetings
# this examples assumes we only have 2 languages, EN and DE
languages = Person.pluck(:language).uniq.sort
@greetings = languages.each_with_object({}) do |language, hash|
hash[language] = Person.new(language: language).say_hello
end
end
end
# @greetings should return the following hash
=> {
"DE" => "Guten Tag",
"EN" => "Hello"
}
同样,也可以在需要时在控制器操作方法内直接调用类方法,例如在模型中,您可能在Person模型内定义了这样的类方法。
def self.languages
pluck(:language).uniq.sort
end
可以从任何控制器或其他适当的类中调用此方法,例如:
def languages
@people_count = Person.count # active record method to get number of people in database
@languages = Person.languages
end
您可以在控制器动作的视图内使用它的地方
<div>
There are <%= @people_count %> total people in the system.
Of them, <%= @languages.count %> languages are spoken.
Those include the following:
<ol>
<% @languages.each do |language| %>
<li><%= language %></li>
</ol>
</div>