代码之家  ›  专栏  ›  技术社区  ›  Raphomet

困难的named_scope情况

  •  1
  • Raphomet  · 技术社区  · 17 年前

    因此,在讨论模型中,我们有以下内容:

    has_many :taggings
    has_many :tags, :through => :taggings
    

    我试图创建一种简单的方法,从一个用户那里检索讨论中的所有标签。理想情况下,named_scope将被明智地使用,以保持事物的整洁。我认为它应该看起来像这样:

    tags = @discussion.tags.from_user(@user)
    

    在Tag类中编写这个named_scope变得非常困难。它应该是什么样子的?我需要以某种方式将其与Taggings表连接起来吗?

    3 回复  |  直到 17 年前
        1
  •  1
  •   Ian Terrell    17 年前

    class Tag < AR::Base
      named_scope :from_user, lambda { |user| 
        { :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] } 
      }
    end
    
        2
  •  0
  •   Thorbjørn Hermansen    17 年前

    tags = @discussion.taggings.find_by_user(@user).map(&:tag)
    

    taggings.find_by_user_id(@user.id)

        3
  •  0
  •   John Topley    17 年前

    我还没有机会测试这个,但我认为它可能会奏效:

    class Discussion < ActiveRecord::Base
      has_many :taggings
      has_many :tags, :through => :taggings
    end
    
    class Tagging < ActiveRecord::Base
      belongs_to :discussion
      belongs_to :tag  
    end
    
    class Tag < ActiveRecord::Base
      has_many :taggings
      has_many :discussions, :through => :taggings
    
      named_scope :by_user do
        def named(user) do
          Tagging.find_by_user_and_discussion(user, discussion).tags
        end 
      end
    end
    

    这样使用它:

    tags = @discussion.tags.by_user.named(@user)