【问题标题】:Rails 4 has_many throughRails 4 has_many 通过
【发布时间】:2013-06-25 14:51:36
【问题描述】:

我在 Rails 4 中有以下代码:

  POST_MODEL_TO_INT = {text_post: 1, video_post: 2}

  class Label < ActiveRecord::Base
  end

  module PostBase
    include do
      has_many :posts_to_labels, :foreign_key => :post_id, :conditions => { post_model_id: POST_MODEL_TO_INT[self.name.underscore.to_sym] }
      has_many :labels, :through => :posts_to_labels
    end
  end

  class TextPost
    include PostBase
  end

  class VideoPost
    include PostBase
  end

  class PostsToLabel < ActiveRecord::Base
    belongs_to :post
    belongs_to :label
  end


  TextPost.first.labels => return labels collection

我必须向Label 模型添加什么才能从标签实例中获取所有帖子?

Label.first.posts # -> return collection of posts Video, Text ....
Label.first.text_posts # -> return collection of posts Text .... 

【问题讨论】:

  • 看起来你真的在重塑polymorphic associations
  • 是的,我也这么认为,但不幸的是我不能;无法更改发布资源代码

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


【解决方案1】:
class Label < ActiveRecord::Base
  has_many :posts_to_labels, :conditions => { post_model_id: 2 }
  has_many :text_posts, :through => :posts_to_labels
end

class PostsToLabel < ActiveRecord::Base
  belongs_to :post
  belongs_to :label
  belongs_to :text_post, :foreign_key => :post_id
end

我找到了单一资源的解决方案,但不明白为什么我需要将 has_many 添加到 PostsToLabel 中?

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2014-12-16
    • 2013-11-24
    • 1970-01-01
    相关资源
    最近更新 更多