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

前端 未结 8 1721
终归单人心
终归单人心 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 06:56

    In your model,

    class Contact
      self.email_providers = %w[Gmail Yahoo MSN]
      validates :email_provider, :inclusion => email_providers
    end
    

    In your form,

    <%= f.select :email_provider, 
        options_for_select(Contact.email_providers, @contact.email_provider) %>
    

    the second arg of the options_for_select will have any current email_provider selected.

提交回复
热议问题