2010-05-05 51 views
0

我不知道我在做这些正确的。如何将新条目添加到多个has_many关联?

我有3个模型,帐户,用户和事件。

帐户包含一组用户。每个用户都有自己的用户名和密码用于登录,但他们可以在同一帐户下访问相同的帐户数据。

事件是由用户创建的,同一帐户中的其他用户也可以读取或编辑它。

我创建了以下迁移和模型。


用户迁移

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 

帐户迁移

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 

事件迁移

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 

帐户模式

class Account < ActiveRecord::Base 
    has_many  :users 
    has_many  :events 
end 

用户模式

class User < ActiveRecord::Base 
    belongs_to :account 
end 

事件模型

class Event < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :user 
end 

左右....

  1. 这是设置是否正确?
  2. 每次用户创建一个新帐户时,系统都会询问用户信息,例如,用户名和密码。我如何将它们添加到正确的表格中?
  3. 如何添加新事件?

对于这么长的问题,我感到抱歉。我并不十分理解处理这种数据结构的方式。谢谢你们回答我。:)

+0

您确定要自动创建用户名和密码吗?这不是通过表单向用户提供的吗? – Tarscher 2010-05-05 08:03:32

+0

用户在帐号注册过程中需要输入自己的用户名和密码。感谢好友 – 2010-05-05 08:12:58

回答

2

这看起来像has_many :through工作(向下滚动找到:through选项)

如果您需要知道创建事件的用户,那么你应该只指定事件真正属于用户:

class Event < ActiveRecord::Base 
    belongs_to :user 
end 

然而,帐户可以“抓取”他们用户的事件。您指定这样的:

class User < ActiveRecord::Base 
    belongs_to :account 
end 

class Account < ActiveRecord::Base 
    has_many :users 
    has_many :events, :through => :users 
end 

的迁移将是一样的,你写了AccountUser。对于Event您可以删除account_id

class CreateEvents < ActiveRecord::Migration 
    def self.up 
    create_table :events do |t| 
     t.integer  :user_id 
     t.string  :name 
     t.string  :location 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :events 
    end 
end 

然后您的活动可以这样创建:

# These two are equivalent: 
event = user.events.create(:name => 'foo', :location => 'bar') 
event = Event.create(:user_id => user.id, :name => 'foo', :location => 'bar') 

注意,这将创建并保存inmediately事件。如果您想在不保存的情况下创建事件,则可以使用user.events.buildEvent.new代替。

上的帐户的has_many :through将让你得到所有事件的一个帐户:

user.events   # returns the events created by one user 
account.events  # returns all the events created by the users of one account 
user.account.events # returns the events for the user's account 

最后一点,请注意,您在这里重新发明轮子了很多。有很好的解决方案来管理用户和权限。

我建议你有管理权限看看deviserailscast)或authlogicrailscast),用于管理您的帐户,并declarative_authorizationrailscast)或cancanrailscast)。我个人的选择是设计和声明授权。前者比authlogic更容易安装,后者比cancan更强大。

问候,祝你好运!

+0

。我长期寻找这些宝石。将深入研究设计和声明授权。 – 2010-05-05 09:24:18

相关问题