Reputation: 205
I have a users model in my rails application. It has a name attribute only along with email & password added to it for login via Devise. I want to create a model Profile for users. How shall I create it. Either by adding profile attributes to existing User model or by creating a model Profile and adding a belongs_to association to it.
Upvotes: 4
Views: 2278
Reputation: 6948
Adding more attributes to your user model will make your user object a bit heavy and is not the best idea given that you'll be calling that object quite often. For instance, to verify a user, you don't need to load the profile attributes like location or date of birth, which the current_user helper would. So, its better to extract profile attributes in a separate model and adopt either of gabreilhilal's approaches.
Upvotes: 6
Reputation: 10769
Well, it depends on the requirements you have.
If a user can have only one profile
and you are just going to add some attributes related to the user
, there is no reason to create a new class to it.
However, even if a user can have only one profile, you might want to do some normalisations. If so, you might remove some attributes from the users
table to create a table profiles
, and you will have a one-to-one relationship.
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
Well... depending on your requirements, you might have a situation where a user might have more than one profile. If so:
class User < ActiveRecord::Base
has_many :profiles
end
class Profile < ActiveRecord::Base
belongs_to :user
end
To summarise, there is no right or wrong... it will depend on the requirements you have, as well as you design decision.
Upvotes: 5