【问题标题】:Ruby: specify has_many :through association when several has_many :through associations are givenRuby:当给出多个 has_many :through 关联时,指定 has_many :through 关联
【发布时间】:2015-12-17 04:24:07
【问题描述】:

我有一个简单的数据设置,其中包含一个用户模型和一个任务模型。 在这两个模型之间,我有两个 has_many :through 关联:Fellowships 和 Assignements。总的来说,我想为一个任务指定几个追随者和几个受让人。

我现在想针对特定任务显示所有受让人和所有关注者。 如果只有一个关联,我可以简单地做@task.users。因为我有两个关联,所以我想指定通过哪个关联来获取所有用户。

查看我的代码:

class User < ActiveRecord::Base
    has_many :assignments
    has_many :tasks, through: :assignments

    has_many :fellowships
    has_many :tasks, through: :fellowships
end

class Task < ActiveRecord::Base
    has_many :assignments
    has_many :users, through: :assignments

    has_many :fellowships
    has_many :users, through: :fellowships
end

class Assignment < ActiveRecord::Base
      belongs_to :user
      belongs_to :task
end

class Fellowship < ActiveRecord::Base
      belongs_to :user
      belongs_to :task
end

假设我有一个任务

@task = Task.first

我现在想让所有受让人和所有追随者都拥有类似的东西

@assignees = @task.users “过度关联分配”

@followers = @task.users“超过关联关注”

但我不知道该怎么做。

感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    你可以这样写。

    has_many :assignment_tasks ,通过: :assignments ,来源: :task

    has_many :fellowship_tasks,通过::fellowships,来源::task

    【讨论】:

    • 那么如果我将这些 assigenment_tasks 和 Fellowship_tasks 添加到我的模型关联中,我可以使用@assignees = @task.assignment_users@followers = @task.fellowship_users吗?
    • assigneesfollowers 代替 assignment_tasks 和 Fellowships_tasks 怎么样。这样,您可以使用@task.followers@task.assignees 获取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多