簡體   English   中英

如何使用simple_form_for在視圖中動態生成單選按鈕?

[英]How to dynamically generate radio buttons in the view with simple_form_for?

我想從simple_form中的選項數組生成單選按鈕列表。 用戶選擇的任何選項都將作為該特定字段的數據發送。 options數組可以是一個簡單的數組,也可以是一個哈希數組,沒關系。 另外,我還需要確保選擇當前值的能力。 最好的方法是什么?

只需在控制器中聲明另一個實例變量並在視圖中使用它?

控制器內部動作:

def whatever_action
  @user = # whatever
  @options = # however you get the options
end

然后以以下形式:

<%= f.collection_radio_buttons :options, @options, :first, :last %>

IMO最好在輔助方法中放置此選項數組,但各取其用。

在這種情況下,您可以利用OpenStruct,它將為您提供干凈的訪問器,因此您無需詢問...我的鍵符號還是字符串?

然后,您可以將其與simple_form的label_method / value_method選項一起使用。

在助手中

# at top of helper module
require 'ostruct' 
module ApplicationHelper # (or whatever helper you want)
...

  # passed as an array of hashes, each hash composed of {id: __, value: "blah"}
  def dynamic_options(initial_values = [])
    initial_values.each do |hash_item|
      OpenStruct.new(hash_item)
    end
  end

...
end

然后來看

f.collection_radio_buttons :options, collection: dynamic_options, :id, :value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM