How to add a new entry to a multiple has_many association?

Posted by siulamvictor on Stack Overflow See other posts from Stack Overflow or by siulamvictor
Published on 2010-05-05T06:35:57Z Indexed on 2010/05/05 8:28 UTC
Read the original article Hit count: 162

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....

  1. Is this setting correct?
  2. 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?
  3. 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. :)

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about has-many