defmodule Resources.Follow do
relationships do
belongs_to :follower, User, attribute_type: :integer
belongs_to :followee, User, attribute_type: :integer
end
actions do
create :create_with_username do
argument :username, :ci_string, allow_nil?: false
change manage_relationship(:username, :followee, value_is_key: :username, use_identities: [:uniq_username])
end
end
end
In Follow resource, there are two foreign keys follower_id, followee_id.
They are integers.
But I want to find user with username and relate it with change manage_relationship(:username, :followee, value_is_key: :username, use_identities: [:uniq_username])
this code.
The value_is_key option basically makes the value in your map act as the key for managing relationships. When you set it to true, it means the map’s value is used as the key, which is great if the value itself is something important or unique. If there’s a particular scenario of if something’s still unclear, just share a bit more info, and it’ll be sorted out.
@zachdaniel
Why does the first action create_by_username doesn’t work, but second action create_by_map work?
I think first action and second action pass same amount of information to manage_relationship.
What value_is_key does is rewrite each value given to manage_relationship, to be a map with a single key (the value_is_key option) and a value of the original value. For example:
# in create_by_username
#action input
%{
username: "foo"
}
# what gets passed into `manage_relationship`
%{username: "foo"}
# we take the value `"foo"`, and put it in a map with the key `username`
Contrast that with create_by_map, which may make it more clear why create_by_map doesn’t work:
# in create_by_map
# action_input
%{
map: %{id: 10} # or %{username: "username"}
}
# what gets passed into `manage_relationship`
%{
username: %{id: 10} # or %{username: "username"}
}
# we take the value `%{id: 10}`, and put it in a map with the key `username`
Naturally, username: %{id: 10} is not what you want.
I’d have to see what you are passing to Follow.create_by_username. Follow.create_by_map!does work if you pass it in the way you are passing it. But I’m assuming what you want is something like Follow.create_by_username("zach").
I implemented this using the alembic/realworld fork.
In my private repository, the “follow_by_username” test fails, but it doesn’t fail in this example.
I need to figure out what I missed.