ruby-on-rails - 对多个模型使用一项操作

标签 ruby-on-rails ruby-on-rails-3 model

我有大约 5 个行为非常相似的模型。事实上,我希望他们分享一个展示它们的 Action 。例如,对于汽车、卡车、货车模型,我想要一个如下的定义:

[Car, Truck, Van].each do |Model|
  action_for Model do #I made this up to show what I mean
    def index
      @model = Model.all
      @model_names = @model.map(&:name).join(', ')
    end
  end
end

我该如何做到这一点,这样我就不会在多个 Controller 中定义相同的操作? (这不是很干)它会在 application_controller 中吗?如果问得不算太多,我该怎么做才能让他们也分享观点?

更新

如果这可以在各个 Controller 之外,那就更好了。如果我能让它正常工作,我什至不需要生成单独的 Controller 。

最佳答案

这样的东西对你有用吗?

module Display
  def index
    m = self.class.to_s.chomp('Controller').classify.constantize
    @model = m.all
    @model_names = @model.map(&:name).join(', ')
  end
end

在 Controller 中:

class CarsController < ApplicationController
  include Display 
end

class TrucksController < ApplicationController
  include Display 
end

class VansController < ApplicationController
  include Display 
end

编辑:尝试在没有单独 Controller 的情况下执行此操作

class DisplaysController < ApplicationController
  def index
    @model = params[:model].constantize.all
    @model_names = @model.map(&:name).join(', ')
  end
end

路线.rb

match "display" => "display#index", :as => :display

在 View 中

link_to "Display Cars", display_path(:model => "Car")
link_to "Display Trucks", display_path(:model => "Truck")
link_to "Display Vans", display_path(:model => "Van")

注意:如果您听说过模块的 extend,并且想知道为什么/何时使用 includeextend,请参阅 What is the difference between include and extend in Ruby? (基本上 include 用于实例,extend 用于类方法)。

关于ruby-on-rails - 对多个模型使用一项操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9652323/

相关文章:

ruby-on-rails-3 - Sidekiq 错误未初始化的常量

ruby-on-rails - 使用 Rails 国际化静态页面

ruby-on-rails-3 - Rails wrap_parameters vs include_root_in_json,有什么区别?

ruby-on-rails - ruby on rails 模型中的全局方法

python - 如何解决这个 django OneToOneField 模型错误?

ruby-on-rails - 我怎样才能让我的网站这么快?

ruby-on-rails - 为什么有不同的 Ruby On Rails 版本?

ruby-on-rails - Rails 验证错误消息未显示并给出未定义的方法错误

ruby-on-rails - docker-compose Rails spring 不起作用

.net - 基于 .Net 的建模应用程序的速度改进