【问题标题】:How to obtain different type of collections for the same Model in an Association in Rails 4?如何在 Rails 4 的关联中为同一模型获取不同类型的集合?
【发布时间】:2015-05-06 10:38:31
【问题描述】:

在我的应用程序中,我有一个 User 模型和一个 Job 模型。用户可以发布许多职位,其他用户可以通过发布提案来申请这些职位。然后,职位发布者可以从已申请的用户列表中选择一个用户,稍后该用户将被分配从事此工作。

这意味着 Job 模型应该为 User 提供两种外键,可能类似于 poster_id 和 worker_id。

目前我的模型如下所示:

class Job < ActiveRecord::Base
   belongs_to :user
   has_many :proposals, dependent: :destroy
end

class User < ActiveRecord::Base
   has_many :jobs, dependent: :destroy
   has_many :proposals, through: :jobs
end

class Proposal < ActiveRecord::Base
    belongs_to :job
    belongs_to :user
end

我的问题是,为了按照我描述的方式工作,这些模型之间的正确关联是什么?

例如,我需要访问某个用户发布的职位,以及该用户订阅的职位(worker_id)。这些是不同的集合,但属于同一模型 Job...

类似:

@user.posted_jobs.all
@user.current_jobs.all

这些将为同一个@user 返回不同的作业。

非常感谢帮助。

【问题讨论】:

  • 一个工作可以有多个工人用户吗?

标签: ruby-on-rails ruby rails-activerecord models model-associations


【解决方案1】:

假设您的 Job 在接受提案时只能设置一个工人,您会想要这样的东西:

class Job < ActiveRecord::Base
   belongs_to :poster, class_name: 'User', foreign_key: 'poster_id'
   belongs_to :worker, class_name: 'User', foreign_key: 'worker_id'
   has_many :proposals, dependent: :destroy
end

class User < ActiveRecord::Base
   has_many :posted_jobs, class_name: 'Job', foreign_key: 'poster_id', dependent: :destroy
   has_many :current_jobs, class_name: 'Job', foreign_key: 'worker_id'
   has_many :proposals, through: :jobs
end

class Proposal < ActiveRecord::Base
    belongs_to :job
    belongs_to :user
end

通过这种方式,你可以获得 user.posted_jobs 和 user.current_jobs。

看到这个:Same Model for Two belongs_to Associations

【讨论】:

    【解决方案2】:

    如果你有JobProposal 模型,你可以使用group_by..这样的例子......所以你可以做类似的事情......

    @results = @results.group_by(&:class)
    @jobs = @results[Job]
    @proposals = @results[Proposal] 
    

    【讨论】:

      【解决方案3】:

      所以

      @user.jobs.all #list of all jobs posted by the user
      

      如果你想要用户订阅的工作列表,你必须做更多的工作

      #subscribeds = [] if u want only the list of jobs subscribeds but not posted
      subscribeds = @user.jobs.all # if u want the list of all jobs related to user
      @user.proposals.each do |proposal| 
           @subscribeds << proposal.job
      end
      

      编辑

      对于处理模型的直接方法,您可以这样:

      class User < ActiveRecord::Base
         has_many :proposals
         has_many :subscribeds_jobs, class_name: 'Job', through: :proposals
         has_many :jobs
         def all_jobs
            return self.jobs.all + self.subscribeds.jobs.all
         end
      end
      

      这样,Rails 将通过记录关联恢复提案作业。

      【讨论】:

      • 感谢您的回复。这是否意味着订阅的作业不能像@user.jobs 这样的模型集合来处理,而必须按照您指定的方式“访问”?
      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 2015-02-26
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多