【问题标题】:Is there a way in Active Record to get thereActive Record 中有没有办法到达那里
【发布时间】:2011-07-30 00:57:57
【问题描述】:

我有一个包含多个角色的用户模型,并且该角色有很多用户,都通过一个中间表。最后角色 has_many/has_one 目标。我想通过用户达到目标,或者让我说我想做一些类似用户 has_many :goals through :roles 的事情。当我这样做并尝试设置 user.goals = Goal.all 时。它给出了以下异常。

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection:无法修改关联“User#goals”,因为源反射类“Goal”通过:has_one 关联到“Account”。

有什么办法可以做到这一点。我在 RailsAPI 上没有看到类似的东西。

【问题讨论】:

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


【解决方案1】:

您不需要显式设置它,您应该能够做到;

user.goals

只要您的模型中有以下内容:

has_many :goals, :through=>:joining_table_name

【讨论】:

    【解决方案2】:

    由于您没有发布模型的详细信息,我根据错误猜测如下:

    User has_one Account
    User has_many Goals
    Goal belongs_to User
    Goal has_one Account
    

    如果是这种情况,那么您通过将所有目标关联到一个用户来打破这种模式,因此目标应该有 has_many 而不是 has_one 帐户

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2021-10-21
      • 2012-12-04
      • 2012-03-30
      • 1970-01-01
      • 2013-01-25
      相关资源
      最近更新 更多