【问题标题】:ActiveRecord : Cannot modify association because it goes through more than one other associationActiveRecord : 无法修改关联,因为它通过多个其他关联
【发布时间】:2018-03-20 16:15:32
【问题描述】:

我不确定为什么这个关联无效

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :routes
end

class Route < ActiveRecord::Base
 belongs_to :super_route
 has_and_belongs_to_many :tags
end

class SuperRoute < ActiveRecord::Base
  has_one :route
  has_many :tags, through: :route
end

那么我希望能够做到以下几点

s = SuperRoute.create
s.route = Route.create
s.tags << Tag.create

除非这会引发错误

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly: Cannot modify association 'SuperRoute#tags' because it goes through more than one other association.

这里的根本错误是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:
    class SuperRoute < ActiveRecord::Base
      has_one :route
      has_many :tags     #remove through: :route
    end
    

    【讨论】:

    • 这意味着 SuperRoute 和 Tag 类之间存在外键关系,这正是我要避免的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多