[英]Rails 4 execute associated model method from controller
Let say we have a code: 假设我们有一个代码:
Model: 模型:
class Dog < ActiveRecord::Base
def self.make_noise
puts 'bow-wow'
end
end
Controller: 控制器:
class DogsController < ApplicationController
def index
Dog.make_noise
end
end
This will work, but I would rather like to write the controller index
method code like: AssociatedModel.make_noise
or Model.make_noise
这将起作用,但是我想编写控制器index
方法代码,例如: AssociatedModel.make_noise
或Model.make_noise
Is it possible in Rails to call associated model method without using its class name in code? 在Rails中可以在不使用代码的类名的情况下调用关联的模型方法吗?
This would be useful if I would like to use inheritance and make let say PetsController which will be the base for all pets (or a PetNoise Concern included for every applicable controller) and declare there index method. 如果我想使用继承并让PetsController成为所有宠物的基础(或每个适用的控制器都包含PetNoise Concern)并声明那里的索引方法,这将非常有用。
I'm not sure if I explained this well enough. 我不确定我是否解释得足够好。
OK. 好。 The one way (which i don't like) is to write PetsController
method like this: 一种方式(我不喜欢)是这样编写PetsController
方法:
def index
params[:controller].classify.constantize.make_noise
end
This way if I inherit PetsController
from DogsController
it will still work without defining separate index inside DogsController
. 这样,如果我从DogsController
继承PetsController
,它仍然可以工作,而无需在DogsController
定义单独的索引。 But maybe there are other more neat solutions. 但是也许还有其他更简洁的解决方案。
As I also explained in this answer , you can determine the model using params[:controller]
. 正如我在此答案中所解释的,您可以使用params[:controller]
确定模型。 Like this: 像这样:
params[:controller] # => "dogs"
params[:controller].classify # => "Dog"
Therefore you can write your index action "generically" like this: 因此,您可以像这样“一般”地编写索引操作:
def index
model_class = params[:controller].classify.constantize
model_class.make_noise
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.