tarunsachdeva
tarunsachdeva

Reputation: 463

Rails Dynamic form - Adding serializable fields to a form

I have a User and Setting. Setting has a :serializable field called :custom_links:

In Setting.rb

  serialize :custom_links, Hash

In User.rb

has_one :setting, dependent: :destroy

I'd like to create a form that allows users to set any number of custom links, and store those in the :custom_links hash. Each custom link has a Name and a URL in the hash.

I'm not sure how to structure this form in the view and allow users to dynamically add as many custom links as they want using javascript (and save those in the :custom_links hash). I have other fields in :setting and I have my controller working fine with those fields - I think the only thing I need help with is the view and javascript.

UPDATE for clarification:

When a user completes the form to enter :custom_links, I'd like it to be in the following format:

{
:name => "Google", :url => "http://www.google.com",
:name => "Twitter", :url => "http://www.twitter.com"
}

Also, I'd like to be able to dynamically add 2 text fields for each :custom_link that the user wants to enter.

Any and all help is appreciated.

Thanks

Upvotes: 1

Views: 1529

Answers (1)

Teoulas
Teoulas

Reputation: 2963

I would suggest adding those links as a separate model (eg. has_many :custom_links). As an extra, you'll be able to use AR's validations instead of making your own custom validation methods for the serialized attribute.

You can use nested attributes for these fields. Take at look at the following railscasts episodes:

The second one also shows you how to dynamically add more fields with javascript.

Upvotes: 1

Related Questions