【问题标题】:Default_scope on a join table连接表上的 Default_scope
【发布时间】:2011-07-24 17:14:31
【问题描述】:

我的模型设置如下:

class User
  has_many :items
  has_many :words, :through => :items
end

class Item
  belongs_to :user
  belongs_to :word

  default_scope where(:active => true)
end

class Words
  has_many :items
end

我遇到的问题是 default_scope 未应用于以下关联:

 user.words

而不是这个 SQL:

SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) AND ((`items.active = 1))

我在日志中得到这个 SQL:

SELECT `words`.* FROM `words` INNER JOIN `items` ON `words`.id = `items`.word_id WHERE ((`items`.user_id = 1)) 

我认为这是因为默认范围适用于常规模型及其子关联,但不适用于连接表。

什么是让连接表范围在关联之间工作而无需指定的正确 Rails 方法?有吗?

【问题讨论】:

    标签: ruby-on-rails scope has-and-belongs-to-many has-many-through default-scope


    【解决方案1】:

    在#ruby-on-rails 的 dfr 的帮助下找到了答案。

    在 User 类中,将 has_many 关系设置为:

     has_many :words, :through => :items, :conditions => { "items.active" => true }
    

    这是因为虽然 User 和 Word 之间存在 habtm join 关联,但调用 user.words 时并未实际加载 Item 模型。因此,您必须在 User 模型中应用关联范围。

    希望对某人有所帮助。

    【讨论】:

      【解决方案2】:

      谢谢,它很有帮助。这张票(虽然无效)也有人在讨论它:https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3610-has_many-through-associations-may-not-respect-default_scope-conditions#ticket-3610-17

      就个人而言,我觉得这张票不是无效的。默认范围是默认范围。

      【讨论】:

      • 我同意。似乎应该在调用关联时加载连接模型。我认为这不是为了优化。但是,我认为 join 模型是放置该范围的正确位置,而不是将其挂在 User 模型中的 has_many 方法中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2013-01-30
      • 2011-02-03
      • 1970-01-01
      相关资源
      最近更新 更多