新手问题 Rails API 中方法的参数 options = {} 的有效哈希对?

qq2729877005 · 2017年08月12日 · 最后由 qq2729877005 回复于 2017年08月12日 · 1742 次阅读

在 Rails API 中,我们可以看到很多方法都带有 options = {} 这种参数,那么可以传入哪些有效的哈希对呢?

先来个例子

def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
    Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
end

这个 collection_select 方法中,我知道 html_options = {} 这个参数应该填哪些哈希对是有效的,但 options = {} 这个参数中我目前只知道官方例子中的那一种 prompt: true,而随意填入其他的哈希对都没效果,请问各位大佬它还能填写哪些有效哈希对???

扩展开来看,像其他方法中 options = {} 参数又有哪些有效哈希对???

select(object, method, choices = nil, options = {}, html_options = {}, &block) 
grouped_options_for_select(grouped_options, selected_key = nil, options = {}) 
......

先看文档说有哪些,文档懒得写的话就看代码实现...

要多加大括号才能让 Ruby 知道你还要传值给第二个 Hash

luikore 回复

但人家这个方法的源码就这几行

def (object, method, collection, value_method, text_method, options = {}, html_options = {})
    Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
end

怎么看啊😭

qq2729877005 回复

顺路追,不是么?Tags 那个吧。

nouse 回复

这个我知道,但问题是我不知道这个参数能识别的有效哈希对,打个比方说:

class Post < ActiveRecord::Base
  belongs_to :author
end

class Author < ActiveRecord::Base
  has_many :posts
  def name_with_initial
    "#{first_name.first}. #{last_name}"
  end
end

# 传入 prompt: true
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
# 传入 class: true
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, class: true)

生成

<!--传入 prompt: true-->
<select name="post[author_id]" id="post_author_id">
  <option value="">Please select</option>
</select>

<!--传入 class: true-->
<select name="post[author_id]" id="post_author_id">
</select>

传入 class: true 时,相当于废参,还不如不传

chenge 回复

追过了,但追不到,API 里根本没有 Tags😂 😂

Rei 回复

你是对的

qq2729877005 关闭了讨论。 06月29日 14:33
需要 登录 后方可回复, 如果你还没有账号请 注册新账号