Ruby 在 Rails 上使用 SimpleForm:更改使用 :select 或 :collection_select 时发送的数据

Ruby on Rails with SimpleForm: Changing which data is sent when using :select or :collection_select

我有一个对象,上面有几个字段 - namecode,当然还有 id

使用以下代码,我的控制器正在接收 selected 对象的 id(尽管名称显示在 select 下拉列表中)。

<%= form.input :department_short, label: I18n.t('department'), wrapper_html: {class: 'header'},
                           placeholder: 'Select department', as: :collection_select, collection: @departments, required: false %>

我想要发送一个不同的字段(或者,更好的是,基于一个或多个这些字段的内容)。有没有办法做到这一点?

您可以将 value_method 属性 与 lambda 一起使用,如下所示:

<%= form.input :department_short, label: I18n.t('department'), :value_method => lambda {|t| "#{t.name} - #{t.code}"}, wrapper_html: {class: 'header'},
                           placeholder: 'Select department', as: :collection_select, collection: @departments, required: false %>

像这样,应该从您的对象发送 "name - code" 值,例如。在 lambda 操作中,您可以根据需要操作从对象中获取的值。希望你明白这个想法,这会有所帮助。祝你好运!

编辑:

来自官方文档(https://github.com/plataformatec/simple_form):

Collection inputs accept two other options beside collections:

label_method => the label method to be applied to the collection to retrieve the label (use this instead of the text_method option in collection_select)

value_method => the value method to be applied to the collection to retrieve the value

似乎如果你的模型有一个方法 to_label,它会使用那个方法来标记,所以你不必把 label_method 放在每个 select 你想使用它。该文档没有提到是否有类似的 to_value 方法,但肯定会很好