Reputation: 873
I recently started creating a site where users will be able to join groups and be able to interact with the group. So far I have used devise for the users but I'm now wondering what do I use to create user profiles and even the groups profile. This is my first rails application and I just need some guidance on where to go from here? What tools will I need? What is the best way of doing this?
Upvotes: 1
Views: 1034
Reputation: 4043
Rails is the only tool you need. First you'll need to create the other models in your application. From your description I see a UserProfile and a Group. Rails' generator command will stub those out for you:
$ rails generate model UserProfile
$ rails generate model Group
$ rails generate model Membership
Now you will have user_profile.rb and group.rb in your app/models directory, as well as migrations in db/migrate/create.rb. Next you'll need to tell rails what fields to create in the database by editing the migration script. You are free to include whatever you wish here, but you will at least want foreign keys to relate your data.
def CreateUserProfiles < ActiveRecord::Migration
create_table :user_profiles do |t|
t.belongs_to :user
...
and
def CreateMemberships < ActiveRecord::Migration
create_table :memberships
t.belongs_to :user
t.belongs_to :group
...
Now you can execute your migrations to create the database tables for you:
$ rake db:migrate
And you can use ActiveRecord association class methods to define those relationships in code, so that Rails will take care of the SQL for you.
app/models/membership.rb
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
app/models/user.rb
class User < ActiveRecord::Base
has_one :user_profile
has_many :memberships
has_many :groups, :through => :memberships
...
end
app/models/group.rb
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
app/models/user_profile.rb
class UserProfile < ActiveRecord::Base
belongs_to :user
end
Now you have all the tools in place that you need to give users profiles:
UserProfile.create(:user => User.first, :attr => "value", ...)
Or to put a user in a group:
group = Group.create(:name => "Group 1")
group.users << User.first
Use tools when they save you time, but learn to use the tool on which they all depend first–Rails. Check out the Rails Guides, they are excellent.
Upvotes: 5