Submit form action on show.html.eex for a separate schema

Scenario: You have a Comment schema with an HTML form. After submitting a Comment's :status field with a value of approved, display a “Promote” button in the Comment's show.html.eex, when upon click, some of the data from the Comment is posted to the PromotedComments table.

How would you create a promote button in show.html.eex that pattern matches comment_id in the assigns in order to build the data before inserting to the PromotedComments table? (I might not be asking the question correctly. Before inserting data into the PromotedComments table, I need to gather and format some of it, like format the title, compute a comment rating, etc., but this data does not directly come from the form)

<%= form_for @conn, promote_path(@conn, :create), [method: :post], fn f -> %>
   ....something here....
    <%= submit "Promote" %>
 <% end %>
1 Like

1 solution is to use hidden_input, to pass only the comment_id, and pattern match on the :create action in the PromoteController with the correct params.

<%= hidden_input :comment_id, :comment_id, value: %>

Is this the ideal and only solution?

To me it sounds like a “promotion” is a resource of a comment. If that’s the case it always feels more explicit to me to have that encapsulated within the URL itself. So instead of posting to /promote maybe think about a route like this:

POST /comments/:comment_id/promotions

resources "/comments", CommentController, only: [] do
  resources "/promotions", CommentPromotionController, only: [:create]

A hidden field could work, but it’s much less obvious that :comment_id is a requirement when creating a promotion.