【问题标题】:Can't write unknown attribute for a has_many through source with another has_many to same table无法通过源将 has_many 的未知属性与另一个 has_many 写入同一张表
【发布时间】:2014-11-28 02:31:49
【问题描述】:

我收到错误消息:

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 添加到subscriptions 的subscriptions 集合中Account。

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord has-many-through ruby-on-rails-4.2


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多