1

我收到错误:

ActiveModel::MissingAttributeError: can't write unknown attribute `[:account_id, :list_id]`

楷模:

class Account < ActiveRecord::Base
  has_many :accounts_lists
  has_many :subscriptions, -> {uniq}, :through => :accounts_lists, source: :list
  has_many :lists, foreign_key: 'creator_id'
end

class List < ActiveRecord::Base
  has_many :accounts_lists
  has_many :subscribers, -> {uniq}, :through => :accounts_lists, source: :account
  belongs_to :creator, class_name: 'Account'
end

class AccountsList < ActiveRecord::Base
  self.primary_key = [:account_id, :list_id]
  belongs_to :account
  belongs_to :list
end

我正在尝试运行种子方法并在以下命令中将列表添加到帐户:

a = Account.create(email: 'email', password: 'secret', password_confirmation: 'secret')
list1 = List.create(creator: a, list_type: music, name: "a's list 1")
a.subscriptions << list1

account.lists由于应用程序的性质,我已经更改了多对多连接的典型名称。一个帐户可以有许多它订阅的列表,以及它是其创建者的许多列表。

List我相信,从错误的措辞方式来看,很难找到正确的关联来subscriptionsAccount.

有任何想法吗?

4

1 回答 1

1

因此,在阅读了所有文档并查看了我的需求和 and 的配置选项之后has_many :through,我意识到由于连接的性质,has_and_belongs_to_many我并不真正需要我需要的配置选项来准确定义我需要的连接是什么样的。我决定尝试这个选项。以下是任何未来遇到同样问题的谷歌员工的工作代码。has_many :throughhas_and_belongs_to_many

class Account < ActiveRecord::Base
    has_and_belongs_to_many :subscriptions, -> {uniq}, class_name: 'List', join_table: 'accounts_lists', foreign_key: 'subscription_id', association_foreign_key: 'subscriber_id'
    has_many :lists, foreign_key: 'creator_id'
end

class List < ActiveRecord::Base
    has_and_belongs_to_many :subscribers, -> {uniq}, class_name: 'Account', join_table: 'accounts_lists', foreign_key: 'subscriber_id', association_foreign_key: 'subscription_id'
    belongs_to :creator, class_name: 'Account', foreign_key: 'creator_id'
end

只是为了指出我遇到的另一个有趣的连接场景如下:

class List < ActiveRecord::Base
    has_and_belongs_to_many :parents, -> {uniq}, class_name: 'List', join_table: 'lists_lists', foreign_key: 'parent_id', association_foreign_key: 'child_id'
    has_and_belongs_to_many :children, -> {uniq}, class_name: 'List', join_table: 'lists_lists', foreign_key: 'child_id', association_foreign_key: 'parent_id'
end

这是一个多对多,基本上一个List可以拥有Lists,而后者又可以拥有Lists,可以拥有更多Lists等等,等等……

希望这可以帮助其他人在未来解决这个问题......不过......如果有人知道如何使用 a 来做到这一点,has_many :through我仍然很想知道这是否可以使用这种类型的连接。

于 2014-10-04T04:15:17.190 回答