【问题标题】:Collection Select Helper in Rails 3Rails 3 中的集合选择助手
【发布时间】:2014-03-06 13:39:28
【问题描述】:

我有一个关于 Rails 3 中的 collection_select 帮助器的快速问题。

我想创建一个下拉字段,让用户可以从列表中选择一个国家/地区。

我的代码目前看起来像这样:

<%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>

当我在页面上提交时,我在国家/地区的参数中看到类似这样的内容:

"country"=>{"id"=>"Antilles"}

我真正想要的是在下拉列表中选择的国家/地区的 ID,而不是哈希格式。所以结果会更像:

"country"=> 1(所选国家/地区的 id)

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby helper


    【解决方案1】:

    替换

    <%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>
    

    与

    <%= collection_select(:model_object,:country,SyncedCountry.order('name ASC'),:name,:name,{},{:class => "input-xlarge"}) %>
    

    model_object 是传递给表单的对象。如果它是user 的表单并且您的表单看起来像form_for(@user),则将:model_object 替换为:user。

    因此,参数看起来像 "user"=&gt;{"country"=&gt;"Antilles"},假设您正在为用户设置国家/地区。

    【讨论】:

      【解决方案2】:

      来自documentation:

      collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) public ...

      :value_method 和 :text_methodparameters 是要调用的方法 在集合的每个成员上。返回值用作值 每个&lt;option&gt;标签的属性和内容,分别。他们能 也可以是响应调用的任何对象,例如 proc,它将是 调用集合的每个成员来检索值/文本。

      那就试试吧:

      <%= collection_select(:country,:id,SyncedCountry.order('name ASC'),:id,:name,{},{:class => "input-xlarge"}) %>
      

      文档中的示例如下所示:

      示例用法(为Post 的实例选择关联的Author, @post):

      collection_select(:post, :author_id, Author.all, :id,
        :name_with_initial, prompt: true)
      

      如果@post.author_id 已经是1,这将返回:

      <select name="post[author_id]">
        <option value="">Please select</option>
        <option value="1" selected="selected">D. Heinemeier Hansson</option>
        <option value="2">D. Thomas</option>
        <option value="3">M. Clark</option>
      </select>
      

      (这将返回“author_id”=>“1”)

      现在,我不熟悉您的模型,但如果您选择用户所在的国家/地区,我认为这应该可行:

          <%= collection_select(:user, :country_id,SyncedCountry.order('name ASC'),:id,:name,{},{:class => "input-xlarge"}) %>
      

      【讨论】:

      • 这很有效,但参数看起来像这样:country"=&gt;{"id"=&gt;"1"} 无论如何不能将参数作为哈希传递,所以我只获取 ID,即“国家”=> 1 .
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多