Ruby on rails 4 使用hstore并为用户保存新值
我的用户模型包含以下值: 姓名、电子邮件、电话、批准等 我正在处理的项目范围包括自定义用户设置,因此我正在使用hstore(我不想创建用户设置表) 在“用户编辑”视图上,我想创建一个名为“颜色”的复选框,该复选框是否选中将决定是否为用户设置了该设置 我已经按如下方式设置了hstore:Ruby on rails 4 使用hstore并为用户保存新值,ruby-on-rails-4,hstore,Ruby On Rails 4,Hstore,我的用户模型包含以下值: 姓名、电子邮件、电话、批准等 我正在处理的项目范围包括自定义用户设置,因此我正在使用hstore(我不想创建用户设置表) 在“用户编辑”视图上,我想创建一个名为“颜色”的复选框,该复选框是否选中将决定是否为用户设置了该设置 我已经按如下方式设置了hstore: class AddHstore < ActiveRecord::Migration def up enable_extension :hstore end def down d
class AddHstore < ActiveRecord::Migration
def up
enable_extension :hstore
end
def down
disable_extension :hstore
end
end
class AddSettingsToUser < ActiveRecord::Migration
def up
add_column :users, :settings, :hstore
end
def down
remove_column :users, :settings
end
end
class AddHstore
并将用户模型更新如下:
class AddHstore < ActiveRecord::Migration
def up
enable_extension :hstore
end
def down
disable_extension :hstore
end
end
class AddSettingsToUser < ActiveRecord::Migration
def up
add_column :users, :settings, :hstore
end
def down
remove_column :users, :settings
end
end
class AddSettingsToUser
这基本上是我的用户编辑视图:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, :class => "form-horizontal user" }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :phone_number %><br />
<%= f.text_field :phone_number %>
</div>
<div class="actions">
<%= f.submit 'Update', :class => 'btn btn-primary' %>
</div>
<% end %>
“表单水平用户”})do | f |%>
“btn btn主节点”%>
在这一点上,我不确定如何实际实现这一功能。“用户编辑”页面允许用户更改其姓名、电话和其他值,但我如何为hstore
设置添加新值?在创建用户的表单中,添加hstore文件,如下所示:
<%= form_for resource, ...do |f| %>
#...
<%= f.fields_for :settings do |settings| %>
<%= settings.text_field :field1 %>
<%= settings.text_field :field2 %>
<% end %>
#....
<% end %>
现在,你完成了。打开rails控制台并尝试一些示例数据,如
User.create(
settings: { field1: 'data1', field2: 'data2' }
)
这很简单,您可以向hstore和update添加新的值,以检查这是否很棒,效果如何,但是我无法从用户编辑视图更新用户。更新成功,但该用户的settings
值返回为nil
@captainrad,据我所知,您的更新现在也在工作。。对吧?:)因此,删除注释:p