Let an admin role create a post for another non-admin user on a blog, nested items


I’m still following the Phoenix Blog tutorial on hackernoon, and tweaking it in a few parts.

I would like to let an admin create a post, but rather than put it under her user name, create it for another non-admin user. This would be selected at the time of creating the post, so in addition to entering the title and body on the form, the admin user can select from a drop-down list of other users to assign this post to.

I would like to maintain the nesting of users and posts (i.e. url remains like user/5/post/1), but in the new template the action user_post_path has to be specified, so the user has to be already known, before the form is rendered (here I am passing all users but @user will only be known after the form is rendered)

<%= render "form.html", changeset: @changeset, action: user_post_path(@conn, :create, @user), users: @users %>

What is the right approach for this? Is there something I can do on the form.html.eex template and the form_for action that checks is user is an admin and modify the action path?

Many thanks!

If you pass user_id from general form to same changeset, not only admins also other users can create posts for other users. Add a user_id dropdown to form if user admin, create new changeset to cast also :user_id and in your controller use that changeset if user admin .

Thanks dokuzbir.

I followed an old SO post (https://stackoverflow.com/questions/32412042/how-do-i-check-if-a-variable-exist-in-eex) and passed users in the new.html.eex template via the assigns option, and to be showed as a drop-down on the form, again using assigns; users would only be set by the controller if the user was an admin in the new action. However, I do not make the check for admin again in the create post action, and use the same changeset (I just switch user_id between the admin and the new user for the post).