How to add a new entry to a multiple has_many association?
- by siulamvictor
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. :)