简体   繁体   English

Active Record中有没有一种方法可以到达那里

[英]Is there a way in Active Record to get there

I have a User model which has_many Roles and the Role has many users, all through an intermediate table. 我有一个has_many角色的用户模型,并且角色有很多用户,全部通过一个中间表。 At the end Role has_many/has_one goal. 最后,角色has_many / has_one目标。 I want to reach goals through user or let me say I want to do something like User has_many :goals through :roles. 我想通过用户达成目标,或者说我想通过:roles做类似用户has_many:goals的事情。 When I do it and try to set user.goals = Goal.all. 当我这样做并尝试设置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. ActiveRecord :: HasManyThroughCantAssociateThroughHasOneOrManyReflection:无法修改关联“ User#goals”,因为源反射类“ Goal”通过:has_one与“ Account”关联。

Is there any way to achieve this. 有什么办法可以做到这一点。 I don't see anything like that on RailsAPI. 我在RailsAPI上看不到任何类似信息。

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

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 如果真是这样,您将通过将所有目标与一个用户相关联来破坏此模型,因此目标应具有has_many而不是has_one帐户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM