如何在选择选项标签中使值属性在轨道中包含网址



我希望选择选项菜单中的值属性包含url,并且单击时应进入特定路径。我正在使用辅助方法来构建路径

法典:

<%= select_tag :account, options_from_collection_for_select(Account.all,build_path_for_airline(id),"name") %>

助手:

def build_path_for_airline(id)
      new_path = Rails.application.routes.recognize_path(request.path)
      new_path[:airline_id] = id
      new_path
    end

不幸的是,它没有按预期工作,谁能让我知道我在这里错过了什么?

根据文档,value_method参数正是方法。您不能使用任意代码块并期望它正常工作。

应将build_path_for_airline实现为模型类中的帮助程序方法,并在options_from_collection_for_select调用中使用该方法。

# app/models/account.rb
class Account
  # ...
  def airline_path
    # Build the airline path for the current account
  end
end
# app/views/...
<%= select_tag :account, options_from_collection_for_select(Account.all, :airline_path, :name) %>

Richard-Degenne 的回答是正确的,但除了将该方法放入模型中之外,还有另一种选择。 options_from_collection_for_select也可以采用 lambda 作为其value_method参数:

<%= select_tag :account, options_from_collection_for_select(
      Account.all,
      ->(account){ build_path_for_airline(account.id) },
      "name")
%>

最新更新