长生不老药递归
Elixir recursion
我有一个组,我可以将其附加到其他模块。该组可以有一个父组:
schema "groups" do
field :name, :string
field :deleted, :boolean
belongs_to :parent, Group
has_many :users_groups, UserGroup, foreign_key: :group_id
timestamps()
end
通过 user_groups 我可以附加用户。现在我想过滤,如果允许用户看到附加的模块。我检查了一下,看看用户是否在附加组中:
def get_visible_module(module, user_id) do
case module.group do
nil -> module
_ ->
case module.group.users_groups do
nil -> module
_ ->
val = Enum.filter(module.group.users_groups, fn(x)->
x.user_id == user_id
end)
case val do
[] ->
case false do
true -> module
false -> nil
end
_ -> module
end
end
end
end
这可能不是最好的代码,但我仍在学习中,所以也欢迎对这部分进行改进:)
现在我的问题是添加一个递归来检查 user_id 是否通过 user_group 附加到一个组,而该组是通过 parent_id 附加的。我被困在这一点上。为了理解:一个模块有一个附加的组。只有组中的用户或通过 parent_id 附加的组中的用户才允许查看该模块。组被构造为一棵树,所以我需要预先加载父组并检查 user_group 是否包含用户并检查每个父组。
希望这是可以理解的。
谢谢
这里是一个粗略的框架,它适应了你的源代码的命名。它应该让您了解如何在 elixir 中进行递归。
# Exit case when a module has no more parent
def get_visible_module(module, nil, user_id) do
user_in_groups?(module.group.users_groups, user_id)
end
# Case when the module has a parent_id
def get_visible_module(module, parent_id, user_id) do
# check the groups for user_id permission followed by the recusive part
user_in_groups?(module.group.users_groups, user_id) and get_visible_module(parent_module, parent_module.parent_id, user_id)
end
# checks if the user is in the group
defp user_in_groups?(users_groups, user_id) do
# check if the use is in one of the groups
true
end
正如@bla 已经提到的,您应该尝试使用模式匹配来清理代码并减少代码的嵌套级别。
我有一个组,我可以将其附加到其他模块。该组可以有一个父组:
schema "groups" do
field :name, :string
field :deleted, :boolean
belongs_to :parent, Group
has_many :users_groups, UserGroup, foreign_key: :group_id
timestamps()
end
通过 user_groups 我可以附加用户。现在我想过滤,如果允许用户看到附加的模块。我检查了一下,看看用户是否在附加组中:
def get_visible_module(module, user_id) do
case module.group do
nil -> module
_ ->
case module.group.users_groups do
nil -> module
_ ->
val = Enum.filter(module.group.users_groups, fn(x)->
x.user_id == user_id
end)
case val do
[] ->
case false do
true -> module
false -> nil
end
_ -> module
end
end
end
end
这可能不是最好的代码,但我仍在学习中,所以也欢迎对这部分进行改进:)
现在我的问题是添加一个递归来检查 user_id 是否通过 user_group 附加到一个组,而该组是通过 parent_id 附加的。我被困在这一点上。为了理解:一个模块有一个附加的组。只有组中的用户或通过 parent_id 附加的组中的用户才允许查看该模块。组被构造为一棵树,所以我需要预先加载父组并检查 user_group 是否包含用户并检查每个父组。
希望这是可以理解的。 谢谢
这里是一个粗略的框架,它适应了你的源代码的命名。它应该让您了解如何在 elixir 中进行递归。
# Exit case when a module has no more parent
def get_visible_module(module, nil, user_id) do
user_in_groups?(module.group.users_groups, user_id)
end
# Case when the module has a parent_id
def get_visible_module(module, parent_id, user_id) do
# check the groups for user_id permission followed by the recusive part
user_in_groups?(module.group.users_groups, user_id) and get_visible_module(parent_module, parent_module.parent_id, user_id)
end
# checks if the user is in the group
defp user_in_groups?(users_groups, user_id) do
# check if the use is in one of the groups
true
end
正如@bla 已经提到的,您应该尝试使用模式匹配来清理代码并减少代码的嵌套级别。