我在rails助手文件中有这样一个方法

def table_for(collection, *args)
 options = args.extract_options!
 ...
end

我希望能够像这样调用这个方法

args = [:name, :description, :start_date, :end_date]
table_for(@things, args)

这样我就可以基于表单提交动态地传递参数.我不能重写这个方法,因为我在太多地方使用它,否则我怎么做呢?

推荐答案

Ruby可以很好地处理多个参数.

Here is是一个很好的例子.

def table_for(collection, *args)
  p collection: collection, args: args
end

table_for("one")
#=> {:collection=>"one", :args=>[]}

table_for("one", "two")
#=> {:collection=>"one", :args=>["two"]}

table_for "one", "two", "three"
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", "two", "three")
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", ["two", "three"])
#=> {:collection=>"one", :args=>[["two", "three"]]}

(从irb剪切和粘贴的输出)

Ruby-on-rails相关问答推荐

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

Rails 6升级没有加载Mongoid,这是一个问题

Puma 工作人员无法在 Ubuntu 20.04 VM 上的 Rails 5.2 中启动

Ruby/Rails 相当于 Python 的 sys.addAuditHook

active_storage.resolve_model_to_route的不同值代表什么意思?

线程如何在 Web 应用程序中工作?

如何在 Arel 中重用单个绑定变量?

如何使用 Vim 插入 ERB 标签?

Rails 4.1 Mailer 预览和设计自定义邮箱

安装mysql2(0.4.8)时出错,Bundler无法继续

Rails:使用 gem 卸载特定版本的库

Ruby on Rails 基本概念总结

rails active admin 部署:找不到文件'jquery-ui'

Rails Associations - has_many => :through - 但相同的模型

如何在 Rails 应用程序中测试 ElasticSearch (Rspec)

Rails: Sprockets::Rails::Helper::AssetNotPrecompiled 在开发中

在 Rails 3 中设置会话超时

将新管理员添加到活动管理员

使用 ActiveRecord 获取列名

在 Rails 3 中突出显示当前页面的最佳方法? -- 有条件地将css类应用于链接