【问题标题】:A difficult named_scope situation一个困难的 named_scope 情况
【发布时间】:2010-10-29 11:45:05
【问题描述】:

在我的应用程序中,用户可以开始和参与讨论。他们还可以标记讨论;当他们这样做时,会创建一个包含标签名称(如果它不存在的话)的标签,并且还会创建一个标签,它会记住哪个用户用什么标签标记了哪个讨论。

所以在讨论模型中我们有这个:

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

我正在尝试创建一种简单的方法来检索一个用户的讨论中的所有标签。理想情况下,named_scopes 将被明智地用于保持事物的美观和清洁。我认为它应该是这样的:

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

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

【问题讨论】:

    标签: ruby-on-rails named-scope


    【解决方案1】:

    您确实需要以某种方式将其与标记表连接起来。方法如下:

    class Tag < AR::Base
      named_scope :from_user, lambda { |user| 
        { :include => :taggings, :conditions => ["taggings.user_id = ?", user.id] } 
      }
    end
    

    【讨论】:

      【解决方案2】:

      我没有机会对此进行测试,但我认为它可能会起作用:

      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)
      

      【讨论】:

        【解决方案3】:

        也许这样就可以了。虽然不是 named_scope 解决方案:

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

        不确定您是否需要在此处使用taggings.find_by_user_id(@user.id)。完成后,您将得到一个数组,其中包含给定用户给定讨论的标记。将该数组映射到 taggings.tag-model (我猜你的标记模型属于一个标签)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-16
          • 2017-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多