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 (with gmail/yahoo/msn as options) and not a text field. How can I do this ?
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 (with gmail/yahoo/msn as options) and not a text field. How can I do this ?
This is a long way round, but if you have not yet implemented then you can originally create your models this way. The method below describes altering an existing database.
1) Create a new model for the email providers:
$ rails g model provider name
2) This will create your model with a name string and timestamps. It also creates the migration which we need to add to the schema with:
$ rake db:migrate
3) Add a migration to add the providers ID into the Contact:
$ rails g migration AddProviderRefToContacts provider:references
4) Go over the migration file to check it look OK, and migrate that too:
$ rake db:migrate
5) Okay, now we have a provider_id, we no longer need the original email_provider string:
$ rails g migration RemoveEmailProviderFromContacts
6) Inside the migration file, add the change which will look something like:
7) Once that is done, migrate the change:
$ rake db:migrate
8) Let's take this moment to update our models:
Contact:
belongs_to :provider
Provider:
has_many :contacts
9) Then, we set up the drop down logic in the _form.html.erb partial in the views:
10) Finally, we need to add the provders themselves. One way top do that would be to use the seed file:
$ rake db:seed
In your model,
In your form,
the second arg of the options_for_select will have any current email_provider selected.
Or for custom options
Please have a look here
Either you can use rails tag Or use plain HTML tags
Rails tag
*above line of code would become HTML code(HTML Tag), find it below *
HTML tag
You can take a look at the Rails documentation . Anyways , in your form :
As you can guess , you should predefine email-providers in another model -
Provider
, to have where to select them from .You create the collection in the
Contact
controller -Adding
to the new, create and edit methods, using a scope for the
by_name
in theProvider
model -app/models/provider.rb
- for the ordering by nameThen in the view -
app/views/contacts/_form.html.erb
- you useFor 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.