I am not sure am I doing these correct.
I have 3 models, Account, User, and Event.
Account contains a group of Users. Each User have its own username and password for login, but they can access the same Account data under the same Account.
Events is create by a User, which other Users in the same Account can also read or edit it.
I created the following migrations and models.
User migration
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.integer :account_id
t.string :username
t.string :password
t.timestamps
end
end
def self.down
drop_table :users
end
end
Account migration
class CreateAccounts < ActiveRecord::Migration
def self.up
create_table :accounts do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :accounts
end
end
Event migration
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.integer :account_id
t.integer :user_id
t.string :name
t.string :location
t.timestamps
end
end
def self.down
drop_table :events
end
end
Account model
class Account < ActiveRecord::Base
has_many :users
has_many :events
end
User model
class User < ActiveRecord::Base
belongs_to :account
end
Event model
class Event < ActiveRecord::Base
belongs_to :account
belongs_to :user
end
so….
- Is this setting correct?
- Every time when a user create a new account, the system will ask for the user information, e.g. username and password. How can I add them into correct tables?
- How can I add a new event?
I am sorry for such a long question. I am not very understand the rails way in handling such data structure. Thank you guys for answering me. 🙂
This looks like a job for has_many :through (scroll down to find the
:throughoption)If you need to know the user that created the event, then you should specify that Event really belongs only to a user:
Accounts, however, can “grab” their user’s events. You specify that like this:
The migrations would be the same as you wrote for
AccountandUser. ForEventyou can remove theaccount_id:Then your events can be created like this:
Notice that this will create and save the event inmediately. If you want to create the event without saving it, you can use
user.events.buildorEvent.newinstead.The
has_many :throughon Accounts will allow you to get all the events for one account:As a final note, please note that you are reinventing the wheel a lot here. There are pretty good solutions out there for managing users and permissions.
I recommend you to have a look at devise (railscast) or authlogic (railscast) for managing your accounts, and declarative_authorization(railscast) or cancan(railscast) for managing permissions. My personal choices are devise and declarative_authorization. The former is easier to install than authlogic, and the later is more powerful than cancan.
Regards, and good luck!