ruby-on-rails – 泛型示例问题
发布时间:2020-12-17 03:58:43 所属栏目:百科 来源:网络整理
导读:我是 Ruby on Rails的新手,作为C#开发人员,当我想重用代码(对于存储库类)时,我可以将它放入类型为 T的基类中.能够做这样的事情: public virtual IEnumerableT GetAll(){ return ContextT.GetAll();} 如果我需要做任何自定义逻辑,我当然可以覆盖我的“用户”
我是
Ruby on Rails的新手,作为C#开发人员,当我想重用代码(对于存储库类)时,我可以将它放入类型为< T>的基类中.能够做这样的事情:
public virtual IEnumerable<T> GetAll() { return Context<T>.GetAll(); } 如果我需要做任何自定义逻辑,我当然可以覆盖我的“用户”存储库中的方法. 在Ruby中,我很熟悉你可以这样做: class UsersController < ApplicationController 这将允许访问ApplicationController中的所有方法及其父类.使用scaffolding时,它会在每个子类中生成以下方法: def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end 我最终得到的是10个具有相同方法的类,但唯一的区别是’User.all’,’Post.all’等. 我如何使这个方法通用,所以我可以将它放在我的ApplicationController类中? 感谢您为Ruby on Rails新手提供的任何帮助. 解决方法
关于脚手架代码的第一件事是它可以被删除,因此:
def index @users = User.all end 除非您打算以其他格式(如json,html,pdf)传递视图,否则不需要respond_to块.如果你仍然觉得需要干掉这种方法,你可以做类似的事情 # app/controllers/concerns/autoload_records.rb module AutoloadRecords included do before_action :load_records,only: :index before_action :load_record,only: [:create,:show,:edit,:update,:destroy] end private def load_records @records = model_class.all end def load_record @record = model_class.find(params[:id]) end def model_class klass = self.class.to_s[/A(w+)sControllerZ/,1] #=> get the name of the class from the controller Constant Object.const_get(klass) end end 并写你的控制器像 class UsersController < ApplicationController include AutoloadRecords def index @records # => #<ActiveRecord::Relation[...]> end def show @record # => #<User ...> end def non_rest_action @record # => nil @records # => nil end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |