How to have a drop down <select> field in a rails form?

前端 未结 8 1722
终归单人心
终归单人心 2020-12-02 06:23

I am creating a scaffold -

rails g scaffold Contact email:string email_provider:string 

but I want the email provider to be a drop down (wi

8条回答
  •  甜味超标
    2020-12-02 07:03

    You create the collection in the Contact controller -

    app/controllers/contacts_controller.erb 
    

    Adding

    @providers = Provider.all.by_name
    

    to the new, create and edit methods, using a scope for the by_name in the Provider model - app/models/provider.rb - for the ordering by name

    scope by_name  order(:name)
    

    Then in the view - app/views/contacts/_form.html.erb - you use

    <%= f.collection_select :provider_id, @providers, :id, :name, include_blank: true %>
    

    For rails forms, I also strongly recommend you look at a form builder like simple_form - https://github.com/plataformatec/simple_form - which will do all the heavy lifting.

提交回复
热议问题