collection_select をわかりやすく簡単に説明してくれる人はいますか? 質問する

collection_select をわかりやすく簡単に説明してくれる人はいますか? 質問する

Rails API ドキュメントを確認していますcollection_selectが、ひどい内容です。

見出しは次のとおりです。

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

そして、これが彼らが提供する唯一のサンプルコードです:

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

単純な関連付け (たとえば、Userhas_many Plans、および がPlanに属するUser) を使用して、構文で何を使用すればよいのか、またその理由を説明できますか?

編集1:また、 または通常のフォーム内でどのように機能するかを説明していただけると嬉しいですform_helper。Web 開発を理解しているものの、Rails については「比較的初心者」の Web 開発者にこれを説明すると想像してください。どのように説明しますか?

ベストアンサー1

collection_select(
    :post, # field namespace 
    :author_id, # field name
    # result of these two params will be: <select name="post[author_id]">...

    # then you should specify some collection or array of rows.
    # It can be Author.where(..).order(..) or something like that. 
    # In your example it is:
    Author.all, 

    # then you should specify methods for generating options
    :id, # this is name of method that will be called for every row, result will be set as key
    :name_with_initial, # this is name of method that will be called for every row, result will be set as value

    # as a result, every option will be generated by the following rule: 
    # <option value=#{author.id}>#{author.name_with_initial}</option>
    # 'author' is an element in the collection or array

    :prompt => true # then you can specify some params. You can find them in the docs.
)

または、次のコードで例を表すこともできます。

<select name="post[author_id]">
    <% Author.all.each do |author| %>
        <option value="<%= author.id %>"><%= author.name_with_initial %></option>
    <% end %>
</select>

これはには記載されていませFormBuilderんが、FormOptionsHelper

おすすめ記事