Active Record 有没有办法到达那里

发布于 2024-10-29 18:25:03 字数 392 浏览 1 评论 0原文

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

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

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

I have a User model which has_many Roles and the Role has many users, all through an intermediate table. At the end Role has_many/has_one goal. I want to reach goals through user or let me say I want to do something like User has_many :goals through :roles. When I do it and try to set user.goals = Goal.all. It gives following exception.

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'User#goals' because the source reflection class 'Goal' is associated to 'Account' via :has_one.

Is there any way to achieve this. I don't see anything like that on RailsAPI.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

错爱 2024-11-05 18:25:03

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

user.goals

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

has_many :goals, :through=>:joining_table_name

You don't need to explicitly set it you should just be able to do;

user.goals

as long as you have the following in your model:

has_many :goals, :through=>:joining_table_name
不必你懂 2024-11-05 18:25:03

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

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

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

Since you did not post the details of the models, I'm guessing the following based on the error:

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

If that is the case, then you're breaking this model by associating all goals to one user, and therefore goal should have has_many and NOT has_one Account

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文