Alright, here is what I tried and it is working quite well.
User model - models/user.rb
class User < ActiveRecord::Base
serialize :settings
attr_accessible :email, :settings_attributes
def settings_attributes=(attributes)
self.settings = attributes
end
end
User controller - controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
redirect_to users_path
else
render :new
end
end
end
User edit page - views/users/edit.html.erb
<h1>Users#edit</h1>
<%= form_for @user do |f| %>
<%= f.fields_for :settings_attributes, OpenStruct.new(@user.settings) do |builder| %>
<% @user.settings.keys.each do |key| %>
<%= builder.text_field key.to_sym %><br />
<% end %>
<% end %>
<%= f.submit %>
<% end %>
When updating the user, the controller receive in the params hash a key named settings_attributes
. By defining a setter in our User model, we are able to edit the serialized settings
attribute.
In the view we are simply looping on all the keys
in the settings
hash and display a textfield
. You may want to display other thing such as textarea
or even select
. This would require to customize the settings
hash in order to know what is the type of the setting you want to display (you could store a key named type
in the hash which hold the type of the setting and a key value
which holds the name of the setting)
Regarding the add_new_link
functionality, you may want to take a look at this railscast http://railscasts.com/episodes/196-nested-model-form-revised
I fired a rails application from scratch and it's working quite well. Let me know if you have any questions.