两个用户实例如何具有相同的帐户

时间:2014-01-09 16:45:21

标签: ruby activerecord ruby-on-rails-4

在我的rails应用程序中,我想创建一个共享帐户(稍后具有不同的访问级别)。我希望用户的两个实例拥有相同的帐户。

我的用户模型has_many :accounts和我的帐户belongs_to :user

当我这样做时,在rails控制台中,例如:

account = Account.first
account.user_id = [1, 2]
account.save

它返回true,但是当我再次检查account.user_id = nil

那我该如何继续呢?

编辑:

帐户模型:

class Account < ActiveRecord::Base

  belongs_to :user

  has_many :products

  validates_presence_of :title

end

和用户模型:

class User < ActiveRecord::Base
  has_many :accounts
  has_many :products, through: :accounts

  accepts_nested_attributes_for :accounts

  validates_presence_of :name

  before_save do
    self.email = email.downcase unless :guest?
  end

  validates :name, presence: true, length: { maximum: 50 }, unless: :guest?

end

编辑2:

我已更新模型关系,因此新的帐户模型为:

class Account < ActiveRecord::Base

  has_and_belongs_to_many :users

  validates_presence_of :title

end

,新的用户模型是:

class User < ActiveRecord::Base
  has_and_belongs_to_many :accounts
  belongs_to :account
  has_many :products, through: :accounts

  accepts_nested_attributes_for :accounts

  validates_presence_of :name

  before_save do
    self.email = email.downcase unless :guest?
  end

  validates :name, presence: true, length: { maximum: 50 }, unless: :guest?

end

我还创建了一个新的迁移,一个accounts_users表

class CreateAccountsUsersJoinTable < ActiveRecord::Migration
  def change
    create_join_table :users, :accounts do |t|
       ## Not sure if this is necessary
       ##t.index [:user_id, :account_id]
       ##t.index [:account_id, :user_id]
       t.belongs_to :user
       t.belongs_to :account
    end
  end
end

我仍然无法拥有多个用户的帐户

0 个答案:

没有答案