Is there a best practices/coherent way to update a

2019-03-27 13:13发布

I'm referring to Rails 3.2's Data Store feature, in which there's the option to store key-value stores in a textfield, even if you're using a relational database like MySQL...it works fine when programmatically manipulating the fields.

But what documentation is there to update these fields from a RESTful HTML form? Or is this something that's not recommended at all? That is, the better solution would be to go to NoSQL?

2条回答
狗以群分
2楼-- · 2019-03-27 13:29

If I understand the question, I think you just need to declare the field name holding the store, and the associated accessors (properties) in the model, like

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

at which point the field works with AR and AREL just like any other, even with forms.

There's very little magic here. The field holds a hash of values; the store declaration lets Rails know that you can reference them like something.weight or something.color, whether reading or writing. Simple and slick. Classic DHH.

查看更多
在下西门庆
3楼-- · 2019-03-27 13:37

although the question is quite old someone else might find it useful, also im pretty 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 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 to add some extra fields from the form ive created 2 attr_accessor in the model:

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

then added the 2 new fields on 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 made a function that check the presence of the new fields and then merge the previous values of the prefs with new ones, like this:

#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
...

done that i return it and pass it to the update_attributes, hope it helped!

查看更多
登录 后发表回答