How to use Form_For to update a hash attribute in a model

A quick warning: I'm pretty new to Rails, and my knowledge is something like cookie-cutter-esque. I know how to do certain things, but I miss this important understanding of why they always work.

I currently have a User model that has a ton of information in it, such as address, email, etc. In addition, it also has a hash called visible. The keys in this hash are each part of the information, and the value is either true or false for whether the user wants the information to be publicly available. Although I'm not sure if this is the best way to go, I cannot think of any other way than to create an integer number of Boolean variables for each bit of information. Finally, I serialize: visible for storage in the database

What I would like, in my edit view, there is a checkbox next to each information field that represents a visible attribute. After reading many other posts related to this topic and trying numerous code variants, I always get some kind of error. The code that looks most intuitively correct for me is as follows:

<%= form_for(@user, :id => "form-info-personal") do |f| %> ... <%= f.label :name %> <%= f.text_field :name %> <%= f.check_box :visible[:name] %> 

But I get an error saying that Symbol cannot be parsed into an integer. I'm not sure if this parsing even tries to happen, if only looking at it: visible as an array and not trying to use: name as an index.

I apologize in advance if this question is trivial / seemingly pointless / is there vital information missing / etc. Any tips, suggestions, links, or something that you would really like, even if they match the lines: "you are doing it completely wrong, go back and do it like that."

-Nick

+4
source share
1 answer

Rails 3.2 is a great addition to ActiveRecord , which allows you to save custom settings in one field.

 class User < ActiveRecord::Base store :settings, accessors: [ :color, :homepage ] end u = User.new(color: 'black', homepage: '37signals.com') u.color # Accessor stored attribute u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor 

So your code might look like this:

 # model class User < ActiveRecord::Base store :settings, accessors: [ :name_visible, :email_visible ] end # view <%= f.label :name %> <%= f.text_field :name %> <%= f.check_box :name_visible %> 
+6
source

Source: https://habr.com/ru/post/1397536/


All Articles