Evaluate the conditions:
- 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| ; - Resource
comments nested in posts , the url the form should be POST posts/60/comments . Adjust: form_for [@post, Comment.new] do |f| ; - The
message comment field is specified in the comment form: f.text_area :message ; - 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.