Rails has_many通过条件上下文

时间:2015-09-29 09:05:18

标签: ruby-on-rails

我有三个模型RoleActionRoleAction以及一些代码:

class Role < ActiveRecord::Base
    has_many :users
    has_many :actions, -> {where role_actions:{status: 1}}, :through => :roleActions
    has_many :actions, :through => :roleActions #other context(manager, etc...)
    has_many :roleActions
end

class Action < ActiveRecord::Base
    has_many :actions, foreign_key: 'parent_id'
    has_many :roleActions
    has_many :roles, through: :roleActions
end

class RoleAction < ActiveRecord::Base
    belongs_to :role
    belongs_to :action
end

当我使用role.actions时,会在role_actions中获得rolestatus == 1的操作。

但我希望当我使用role.actions("manager")(“经理”是上下文名称)时,将返回角色的所有操作。

我该怎么办?

谢谢!

1 个答案:

答案 0 :(得分:1)

  
      
  1. 您需要保持关联snake_case
  2.   
  3. 您不能拥有多个具有相同名称的关联(IE actions
  4.   

这就是我要做的事情:

#app/models/role.rb
class Role < ActiveRecord::Base
   has_many :role_actions
   has_many :actions, through: :role_actions do
      def status(val)
        { where status: val } # @role.actions.status(1)
      end
   end
end

#app/models/role_action.rb
class RoleAction < ActiveRecord::Base
   belongs_to :role
   bleongs_to :action
end

#app/models/action.rb
class Action < ActiveRecord::Base
   has_many :role_actions
   has_many :actions, through: :role_actions
end

你想在Rails中查找scopes - 在你的关联查询中定义条件是不好的做法,然后才想打破它。有些人称之为antipattern

-

如果您有“裸”关联,那么您可以根据需要设置范围。您还可以使用ActiveRecord association extensions为您的关联本身提供特定功能(如上所示)。

  

role.actions("manager")

这可以通过在查找 manager 值时调用Role对象来实现:

@role = Role.find_by name: "manager"
@role.actions #-> all actions for the "manager" role.
相关问题