Is there a best practice / consistent way to update a database field containing a hash key store?

I mean the Rails 3.2 data warehouse function, which has the ability to store key stores in a text field, even if you use a relational database such as MySQL ... it works great when programmatically managing the field.

But what documentation exists to update these fields from a RESTful HTML form? Or is this not recommended at all? That is, the best solution would be to switch to NoSQL?

+7
source share
2 answers

If I understand the question, I think you just need to declare the name of the field that stores the store, and the related objects (properties) in the model, for example

store :settings, accessors: [ :weight, :length, :color ] 

at this moment, the field works with AR and AREL in the same way as with any other, even with forms.

There is very little magic. The field contains a hash of values; a store ad lets Rails know that you can refer to them as something. weight or something.color, whether it is reading or writing. Simple and sleek. Classic DHH.

0
source

although the question is quite old, someone might find it useful, as well as im quite new in ruby โ€‹โ€‹and rails, so there might be a better way to do this.

In the model:

 #user.rb attr_accessible :preferences store :preferences 

then in the form of a partial:

 #views/users/_form.rb <% @user.preferences.each do |k, v| %> <% form.fields_for :preferences, @user.preferences[k] do |p| %> <div class="field"> <%= p.label k %> <br/> <%= p.text_field k, :value => v %> </div> <% end %> <% end %> 

Now add additional fields from the ive form created in attr_accessor model 2:

 attr_accessible ... , :new_pref_key, :new_pref_val attr_accessor ... , :new_pref_key, :new_pref_val 

then added 2 new fields in the form

 <%= f.label :new_pref_key %> <%= f.text_field :new_pref_key %> <%= f.label :new_pref_val %> <%= f.text_field :new_pref_val %> 

on my controller, I created a function that checks for new fields and then combines the previous prefs with the new ones, for example:

 #users_controller.rb ... new_key = params[:user][:preferences][:new_pref_key] new_val = params[:user][:preferences][:new_pref_val] new_preference = { new_key => new_val } current_params = params[:user][:preferences].merge! new_preference ... 

did that i return it and pass it to update_attributes, hope this helps!

0
source

All Articles