Reputation: 5854
Full source code is here https://github.com/tenzan/postfile
Creating a post working fine.
I have a parent element "Conversation" and its child/nested element "Post".
When I click on "Create Post" with nothing entered, it should throw an error "Body can't be blank".
Instead, it giving another error:
conversation.rb
:
class Conversation < ApplicationRecord
belongs_to :contact
has_many :posts
end
post.rb
:
class Post < ApplicationRecord
belongs_to :conversation
belongs_to :author, polymorphic: true
has_rich_text :body
validates :body, presence: :true
end
posts_controller.rb
:
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation
def create
@post = @conversation.posts.new(post_params)
@post.author = current_user
respond_to do |format|
if @post.save
format.html { redirect_to @conversation }
end
end
end
private
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
end
def post_params
params.require(:post).permit(:body)
end
end
I show all posts within from conversation's show.html.erb
:
<p id="notice"><%= notice %></p>
<p>
<strong>Subject:</strong>
<%= @conversation.subject %>
</p>
<p>
<strong>Contact:</strong>
<%= link_to @conversation.contact.name, @conversation.contact %>
</p>
<%= link_to 'Edit', edit_conversation_path(@conversation) %> |
<%= link_to 'Back', conversations_path %>
<div id="posts">
<%= render @posts %>
</div>
<%= render partial: "posts/form", locals: { conversation: @conversation, post: Post.new } %>
Posts's partial _form.html.erb
:
<%= form_with model: [conversation, post], id: "form" do |form| %>
<div>
<% form.object.errors.full_messages.each do |message| %>
<div><%= message %></div>
<% end %>
</div>
<br>
<%= form.rich_text_area :body %>
<%= form.submit %>
<% end %>
Full source code is here https://github.com/tenzan/postfile
Thanks in advance.
Upvotes: 0
Views: 40
Reputation: 1309
You have this block in your posts_controller
, which is where your error is arising:
respond_to do |format|
if @post.save
format.html { redirect_to @conversation }
end
end
Inside a respond_to
block, you should have blocks identified by the format
type, but you've added an if
statement at that top level of the block where Rails is expecting a format.xxx
. Move the if
outside your respond_to
block and you should be fine:
if @post.save
respond_to do |format|
format.html { redirect_to @conversation }
end
else
DO SOMETHING WITH THE ERROR
end
(Also NB that you should handle the error if the post doesn't save, even if it's just to say "Sorry, please try again".)
Upvotes: 1