2015-09-29 96 views
2

我有三个模型RoleActionRoleAction一些代码:Rails的HAS_MANY通过条件方面

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行动,并在role_actions status == 1

但我想当我使用role.actions("manager")(与“经理”是上下文名称)将返回角色的所有行动。

我该怎么办?

谢谢!

+0

http://stackoverflow.com/questions/408872/ rails-has-many-through-find-by-extra-attributes-in-join-model – lokson

+0

你可以用'role.actions.where(name_of_attribute:'manager')'来实现。其中name_of_attribute是存储“manager”值的属性名称 –

回答

1
  1. 你必须保持你的协会snake_case
  2. 你不能有多个同名协会(IE actions

这里就是我想要做的:

#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")

这可以通过简单地调用Role对象仰视经理值时可以实现:

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