Reputation: 9154
A quick warning: I am pretty new to Rails, and my knowledge is somewhat cookie-cutter-esque. I know how to do certain things, but I lack that vital understanding of why they always work.
I currently have a User model that has in it a bunch of information, like address, email, etc. In addition, it also has a hash called visible. The keys in that hash are each of the pieces of information, and the value is either true or false for whether the user wishes that information to be publicly visible. While I'm not sure if this is the best way to go, I can't think of any other way other than making a whole ton of boolean variables for each bit of information. Finally, I serialize :visible for storage in the database
What I would like is in my edit view to have a checkbox beside each field of info that represents the visible attribute. After reading tons of other posts related to this topic and trying numerous variations of code, I always end up with some kind of an error. The code that looks most intuitively correct to 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 message saying that a Symbol cannot be parsed into an integer. I'm not sure where this parse is even trying to happen, unless its viewing :visible as an array and trying to use :name as an index.
I apologize in advance if this question is trivial/seemingly nonsensical/lacking vital information/etc. Any tips, suggestions, links, or what have you would be very appreciated, even if they're along the lines of "you're doing this fundamentally wrong, go back and do it this way".
-Nick
Upvotes: 4
Views: 2326
Reputation: 230336
Rails 3.2 introduces a nice addition to ActiveRecord, which allows you to store arbitrary settings in a single 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 could 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 %>
Upvotes: 6