Hello,
I am just introducing myself to Rails. Please let me know if the above
method is acceptable or if it is not efficient.
I have three tables:
create table users (
id bigserial primary key,
username varchar,
password varchar,
– more system specific data
);
create table user_data_types (
id bigserial primary key,
name varchar,
code varchar,
restriction varchar
);
create table user_data_fields (
id bigserial primary key,
user_id bigint not null references users(id) on delete cascade,
user_data_type_id bigint not null references user_data_types(id) on
delete cascade,
value varchar
);
insert into user_data_types (name, code, restriction) values
(‘Fullname’, ‘fullname’,null);
insert into user_data_types (name, code, restriction) values (‘Zipcode’,
‘zip’,’^[\d]{4}$’);
I have chosen this database-design to make the user data extendable.
I want to access userdata a hash-like way with the user:
user.id: <%= @user.id %>
user.fullname: <%= @user.user_data_fields[:fullname] %>
user.zip: <%= @user.user_data_fields[:zip] %>
So I decided to modify the User model:
class User < ActiveRecord::Base
has_many :user_data_fields
def after_find
def user_data_fields.[](k)
if k.type != Symbol
super
else
self.each { |f| return f.value if
f.user_data_type.code.to_sym == k }
nil
end
end
end
end
Well, this works pretty well. It causes three selects, which can be
reduced to two with using :include option of the find method.
However, since I am beginner, I would like to get some confirmation. Is
the after_find a right place to implement such a class extension? Is
there an easier way that I missed?
Thank you for your time.
Mage