Ruby on rails 具有的作用域具有多个直通关联

Ruby on rails 具有的作用域具有多个直通关联,ruby-on-rails,Ruby On Rails,我有两个模型小部件和功能,它们通过使用WidgetFeature模型有很多关联 class Widget < ActiveRecord::Base has_many :widget_features has_many :features, :through => :widget_features end class WidgetFeature < ActiveRecord::Base belongs_to :feature belo

我有两个模型小部件和功能,它们通过使用WidgetFeature模型有很多关联

  class Widget < ActiveRecord::Base
    has_many :widget_features
    has_many :features, :through => :widget_features
  end

  class WidgetFeature < ActiveRecord::Base
    belongs_to :feature
    belongs_to :widget
    attr_accessible :children_features, :widget_id, :feature_id
  end

 class WidgetFeature < ActiveRecord::Base
   belongs_to :feature
   belongs_to :widget
   attr_accessible :children_features, :widget_id, :feature_id
 end
我有一个widget\u id

所以我做Widget.find\u by\u id Widget\u id

现在我想找到widget_features.children_features为空的这个小部件的所有特性

我不知道怎么做,帮帮我。

试试看

@widget = Widget.find_by_id(widget_id)
@features = @widget.features.conditions("widget_features.children_features IS nil")
编辑

参考号

然后

@widget = Widget.find_by_id(widget_id)
@features = @widget.features

我绕过了命名范围,找到了一个优雅的解决方案。所以,我把它贴在这里,这样其他遇到同样问题的人也可以得到帮助。 我的解决方案为您提供了一种通过关联访问has-many中联接模型的任何列的方法

以下是解决上述问题的方法:

class Widget < ActiveRecord::Base
  has_many :widget_features
  has_many :features, :through => :widget_features

  def leaf_features
    widget_features.leaf_features.map{|widget_feature|widget_feature.feature}
  end
end

class WidgetFeature < ActiveRecord::Base
  named_scope :leaf_features, :conditions => 'children_features IS NULL'
  belongs_to :feature
  belongs_to :widget
  attr_accessible :children_features, :widget_id, :feature_id
end
现在,Widget.find_by_idwidget_id.leaf_功能 将只为您提供以下功能:
children\u features列为空。

如果您粘贴两次WidgetFeature,请提供功能模型。它不起作用。我得到一个未定义的错误方法'conditions',这意味着conditions不是一个方法。-它仍然不起作用,并给我一个SQL错误。错误:您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以获得在第1行使用接近“nil”的正确语法:选择功能。*从功能内部连接功能部件\u features ON features.id=widget\u features.features\u id其中widget\u features.widget\u id=1和widget\u features.children\u features为nil可能应该是NULL@Silver勺子:-更改为nil到为NULL
Feature.all(:joins => :widget_features, :conditions => ["widget_id = ? and children_features is null", some_id])
class Widget < ActiveRecord::Base
  has_many :widget_features
  has_many :features, :through => :widget_features

  def leaf_features
    widget_features.leaf_features.map{|widget_feature|widget_feature.feature}
  end
end

class WidgetFeature < ActiveRecord::Base
  named_scope :leaf_features, :conditions => 'children_features IS NULL'
  belongs_to :feature
  belongs_to :widget
  attr_accessible :children_features, :widget_id, :feature_id
end