There are 4 models. posts. comments, visitors and notifications. When a person adds a comment to a post, he fills in the comment itself, his name and e-mail.

Routes look like this. It is not entirely clear how to submit all the data for your tables in one submit.

resources :posts, only: [:index, :show, :new] do resources :comments end resources :visitors, [:create] 

enter image description here

    2 answers 2

    All data comes to you in the controller. Pick them up from params and create the necessary entries.

    In your case, it will be comments_controller . In params you will have post_id , as well as all the data from your form.

      Evaluate the conditions:

      1. A comment is created in the form. So the Comment model plays a central role. And the form will be form_for Comment.new do |f| ;
      2. Resource comments nested in posts , the url the form should be POST posts/60/comments . Adjust: form_for [@post, Comment.new] do |f| ;
      3. The message comment field is specified in the comment form: f.text_area :message ;
      4. The email and fullname fields are the Visitor fields of the associated model (in the Comment model, we belongs_to :visitor ). For such fields we start in the form fields_for :visitor do |ff|

      The total shape will be something like this (slim):

       = form_for [@post, Comment.new] do |f| = f.text_area :message = f.fields_for :visitor do |ff| = ff.text_field :email = ff.text_field :fullname 

      The controller code will be something like this:

       class CommentsController < ApplicationController def create Comment.create(comment_params) redirect_to post_path(params[:post_id]) end private def comment_params params.require(:comment) .permit(:message, visitor_attributes: [:email, :fullname]) .merge(post_id: params[:post_id]) end end 

      We do not pass the post_id parameter explicitly through the form, but pull it out from the url (for post/60/comments , the post ID 60 will be in params[:post_id] ).

      In the Comment model, we will have something like this:

       class Comment < ActiveRecord::Base belongs_to :visitor accepts_nested_attributes_for :visitor end 

      Thus, ActiveRecord on the emails sent from the form and fullname will create a record of the Visitor model and link it to the created comment.